A database command specifies which particular action you want to perform to the database. The commands are in the form of SQL (Structured Query Language). There are four basic SQL statements that can be passed to the database.
What is a database connection?
A database connection represents a communication channel between you application and database management system (DBMS). The application uses this connection to pass the commands and queries to the database and obtain the results of the operations from the database.
What is a data adapter?
A data adapter is the component that exists between the local repository (dataset) and the physical database. It contains the four different commands (SELECT, INSERT, UPDATE and DELETE). It uses these commands to fetch the data from the DB and fill into the dataset and to perform updates done in the dataset to the physical database. It is the data adapter that is responsible for opening and closing the database connection and communicates with the dataset.
What is a dataset?
A dataset is the local repository of the data used to store the tables and disconnected record set. When using disconnected architecture, all the updates are made locally to dataset and then the updates are performed to the database as a batch.
DataSet or DataReader ?
The data reader is more useful when you need to work with large number of tables, database in non-uniform pattern and you need not execute the large no. of queries on few particular table.
When you need to work on fewer no. of tables and most of the time you need to execute queries on these fewer tables, you should go for the dataset.
It also depends on the nature of application. If multiple users are using the database and the database needs to be updated every time, you must not use the dataset. For this, .Net provides the connection oriented architecture. But in the scenarios where instant update of database is not required, dataset provides optimal performance by making the changes locally and connecting to database later to update a whole batch of data. This also reduces the network bandwidth if the database is accessed through network.
Disconnected data access is suited most to read only services. On the down side, disconnected data access architecture is not designed to be used in the networked environment where multiple users are updating data simultaneously and each of them needs to be aware of current state of database at any time (e.g., Airline Reservation System).
When you need to work on fewer no. of tables and most of the time you need to execute queries on these fewer tables, you should go for the dataset.
It also depends on the nature of application. If multiple users are using the database and the database needs to be updated every time, you must not use the dataset. For this, .Net provides the connection oriented architecture. But in the scenarios where instant update of database is not required, dataset provides optimal performance by making the changes locally and connecting to database later to update a whole batch of data. This also reduces the network bandwidth if the database is accessed through network.
Disconnected data access is suited most to read only services. On the down side, disconnected data access architecture is not designed to be used in the networked environment where multiple users are updating data simultaneously and each of them needs to be aware of current state of database at any time (e.g., Airline Reservation System).
What's the difference between accessing data with dataset or data reader?
The dataset is generally used when you like to employ the disconnected architecture of the ADO.Net. It reads the data into the local memory buffer and perform the data operations (update, insert, delete) locally to this buffer.
The data reader, on the other hand, is directly connected to the database management system. It passes all the queries to the database management system, which executes them and returns the result back to the application.
Since no memory buffer is maintained by the data reader, it takes up fewer resources and performs more efficiently with small number of data operations. The dataset, on the other hand is more efficient when large number of updates are to be made to the database. All the updates are done in the local memory and are updated to the database in a batch. Since database connection remains open for the short time, the database management system does not get flooded with the incoming requests.
The data reader, on the other hand, is directly connected to the database management system. It passes all the queries to the database management system, which executes them and returns the result back to the application.
Since no memory buffer is maintained by the data reader, it takes up fewer resources and performs more efficiently with small number of data operations. The dataset, on the other hand is more efficient when large number of updates are to be made to the database. All the updates are done in the local memory and are updated to the database in a batch. Since database connection remains open for the short time, the database management system does not get flooded with the incoming requests.
What does it mean by connected data access architecture of ADO.Net?
In the connected environment, it is your responsibility to open and close the database connection. You first establish the database connection, perform the interested operations to the database and when you are done, close the database connection. All the changes are done directly to the database and no local (memory) buffer is maintained.
What does it mean by disconnected data access architecture of ADO.Net?
ADO.Net introduces the concept of disconnected data architecture. In traditional data access components, you make a connection to the database system and then interact with it through SQL queries using the connection. The application stays connected to the DB system even when it is not using DB services. This commonly wastes the valuable and expensive database resource as most of the time applications only query and view the persistent data. ADO.Net solves this problem by managing a local buffer of persistent data called data set. Your application automatically connects to the database server when it needs to pass some query and then disconnects immediately after getting the result back and storing it in dataset. This design of ADO.Net is called disconnected data architecture and is very much similar to the connection less services of http over the internet. It should be noted that ADO.Net also provides the connection oriented traditional data access services.
Traditional Data Access Architecture
ADO.Net Disconnected Data Access Architecture
Another important aspect of the disconnected architecture is that it maintains the local repository of data in the dataset object. The dataset object stores the tables, their relationship and different constraints. The user performs operations like update, insert, delete to this dataset locally and finally the changed dataset is stored in actual database as a batch when needed. This greatly reduces the network traffic and results in the better performance.
Traditional Data Access Architecture
ADO.Net Disconnected Data Access Architecture
Another important aspect of the disconnected architecture is that it maintains the local repository of data in the dataset object. The dataset object stores the tables, their relationship and different constraints. The user performs operations like update, insert, delete to this dataset locally and finally the changed dataset is stored in actual database as a batch when needed. This greatly reduces the network traffic and results in the better performance.
Difference between value type and reference type ?
Many programming languages provide built-in data types such as integers and floating-point numbers. These are copied when they are passed in to arguments i.e. they are passed "By Value". In .NET terms, these are called Value Types".
The RunTime supports two kinds of Value Types:
1 Built-in value types
The .NET Framework defines built-in value types such as System.Int32 and System.Boolean which correspond and are identical to primitive data types used in programming languages.
2 User-defined value types
The language you are using will provide functionality to define your own Value Types. These user defined Types derive from System.ValueType. If you want to define a Type representing a value that is a complex number (two floating-point numbers), you might choose to define it as a value type. Why? Because you can pass the Value Type efficiently "By Value". If the Type you are defining could be more efficiently passed "By Reference", you should define it as a class instead. Variables of Reference Types are referred to as objects. These store references to the actual data.
The following are the Reference Types:
• class
• interface
• delegate
This following are the "built-in" Reference Types:
• object
• string
The RunTime supports two kinds of Value Types:
1 Built-in value types
The .NET Framework defines built-in value types such as System.Int32 and System.Boolean which correspond and are identical to primitive data types used in programming languages.
2 User-defined value types
The language you are using will provide functionality to define your own Value Types. These user defined Types derive from System.ValueType. If you want to define a Type representing a value that is a complex number (two floating-point numbers), you might choose to define it as a value type. Why? Because you can pass the Value Type efficiently "By Value". If the Type you are defining could be more efficiently passed "By Reference", you should define it as a class instead. Variables of Reference Types are referred to as objects. These store references to the actual data.
The following are the Reference Types:
• class
• interface
• delegate
This following are the "built-in" Reference Types:
• object
• string
What is serialization in .NET and what are the ways to control serialization?
Serialization is the process of converting an object into a stream of bytes. On the other hand Deserialization is the process of creating an object from a stream of bytes. Serialization/Deserialization is used to transport or to persist objects. Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly are converted to a stream of bytes. Which is then written to a data stream. Upon the object's subsequent deserialized, an exact clone of the original object is created.
Binary serialization preserves Type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example: An object can be shared between different applications by serializing it to the clipboard.
You can serialize an object to a stream, disk, memory, over a network, and so forth. Remoting uses serialization to pass objects "By Value" from one computer or application domain to another. XML serialization serializes only public properties and fields and does not preserve Type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data.
As XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is also an open standard, which makes it an attractive choice too. There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.
Binary serialization preserves Type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example: An object can be shared between different applications by serializing it to the clipboard.
You can serialize an object to a stream, disk, memory, over a network, and so forth. Remoting uses serialization to pass objects "By Value" from one computer or application domain to another. XML serialization serializes only public properties and fields and does not preserve Type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data.
As XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is also an open standard, which makes it an attractive choice too. There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.
ADD-INS For Microsoft - Excel using .Net
Step:1 :- CREATE THE C# PROJECT(Class lib Application)
Step:2 :- Set the project properties Register for COM Interop to TRUE
#region Using Directives //Using Interop services
using System;
using System.Runtime.InteropServices;
namespace NewAddInFunctionality
{
[ClassInterface(ClassInterfaceType.AutoDual)]
public class AddINFunctions
{
public AddINFunctions()
{
}
Add Method
public double Add2(double v1, double v2)
{
return v1 + v2;
}
Multiply Method
public double Multiply(double v1, double v2)
{
return v1 * v2;
}
Divide Method
public double Divide(double v1, double v2)
{
return v1 * v2;
}
Mod Method
public double MOD(double v1, double v2)
{
return v1 % v2;
}
[ComRegisterFunctionAttribute]
public static void RegisterFunction(Type funType)
{
Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(
"CLSID\\{" + funType.GUID.ToString().ToUpper() +
"}\\Programmable");
}
[ComUnregisterFunctionAttribute]
public static void UnregisterFunction(Type funType)
{
Microsoft.Win32.Registry.ClassesRoot.DeleteSubKey(
"CLSID\\{" + funType.GUID.ToString().ToUpper() +
"}\\Programmable");
}
}
}
Step :3 Build the Project Get the DLL
Step :4 GO To Excel and Open a WorkBook
Step : ADDINS select methods and type ADD(3 + 7) then result will be 10
Step:2 :- Set the project properties Register for COM Interop to TRUE
#region Using Directives //Using Interop services
using System;
using System.Runtime.InteropServices;
namespace NewAddInFunctionality
{
[ClassInterface(ClassInterfaceType.AutoDual)]
public class AddINFunctions
{
public AddINFunctions()
{
}
Add Method
public double Add2(double v1, double v2)
{
return v1 + v2;
}
Multiply Method
public double Multiply(double v1, double v2)
{
return v1 * v2;
}
Divide Method
public double Divide(double v1, double v2)
{
return v1 * v2;
}
Mod Method
public double MOD(double v1, double v2)
{
return v1 % v2;
}
[ComRegisterFunctionAttribute]
public static void RegisterFunction(Type funType)
{
Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(
"CLSID\\{" + funType.GUID.ToString().ToUpper() +
"}\\Programmable");
}
[ComUnregisterFunctionAttribute]
public static void UnregisterFunction(Type funType)
{
Microsoft.Win32.Registry.ClassesRoot.DeleteSubKey(
"CLSID\\{" + funType.GUID.ToString().ToUpper() +
"}\\Programmable");
}
}
}
Step :3 Build the Project Get the DLL
Step :4 GO To Excel and Open a WorkBook
Step : ADDINS select methods and type ADD(3 + 7) then result will be 10
Send Email using Gmail in ASP.Net
protected void btnSendEmail_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.To.Add("saurabhjnumca@gmail.com");
mail.To.Add("saurabh_singh_jnu06@yahoo.co.in");
mail.From = new MailAddress("sandeepjnumca@gmail.com");
mail.Subject = "HI this is a test mail for learners using .Net";
string Body = "Hi Friends, this mail is a test mail"+
"sending this mail through Gmail in ASP.NET";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Credentials = new System.Net.NetworkCredential ("sandeepjnumca@gmail.com","GmailPassword");
smtp.EnableSsl = true;
smtp.Send(mail);
}
{
MailMessage mail = new MailMessage();
mail.To.Add("saurabhjnumca@gmail.com");
mail.To.Add("saurabh_singh_jnu06@yahoo.co.in");
mail.From = new MailAddress("sandeepjnumca@gmail.com");
mail.Subject = "HI this is a test mail for learners using .Net";
string Body = "Hi Friends, this mail is a test mail"+
"sending this mail through Gmail in ASP.NET";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Credentials = new System.Net.NetworkCredential ("sandeepjnumca@gmail.com","GmailPassword");
smtp.EnableSsl = true;
smtp.Send(mail);
}
SQL Tools(DROP , TRUNCATE)
DROP TABLE :-
DROP TABLE table_name
DROP DATABASE :-
DROP DATABASE database_name
TRUNCATE TABLE :-
We use truncate statement if we want to delete the values of the table not the table itself. Like :-
TRUNCATE TABLE table_name
DROP INDEX :-
DROP INDEX table_name.index_no
DROP TABLE table_name
DROP DATABASE :-
DROP DATABASE database_name
TRUNCATE TABLE :-
We use truncate statement if we want to delete the values of the table not the table itself. Like :-
TRUNCATE TABLE table_name
DROP INDEX :-
DROP INDEX table_name.index_no
SQL Tools(Check , DEFAULT, CREATE INDEX)
Check :-
CREATE TABLE SHIP_Orders
(
@O_ID INT NOT NULL,
@ORDER_NAME VARCHAR(25),
@ORDER_ADDRESS VARCHAR(45),
CHECK(@O_ID>2)
)
DEFAULT :-
We can provide default values to the table like in the above table :-
CREATE TABLE SHIP_ORDERS
(
@O_ID INT NOT NULL,
@ORDER_NAME VARCHAR(25) DEFAULT 'SLITTING',
@ORDER_ADDRESS VARCHAR(45) DEFAULT 'DELHI AIRPORT',
CHECK(@O_ID>2)
)
TO ALTER DEFAULT VALUE :-
ALTER TABLE SHIP_ORDERS
ALTER COLUMN @ORDER_NAME SET DEFAULT 'SPLIT'
TO DROP DEFAULT VALUES :-
ALTER TABLE SHIP_ORDERS
ALTER COLUMN @ORDER_NAME DROP DEFAULT
CREATE INDEX :-
CREATE INDEX index_name
ON table_name (column_name)
LIKE :-
CREATE INDEX index
ON SHIP_ORDERS (@ORDER_NAME,@ORDER_ADDRESS)
CREATE TABLE SHIP_Orders
(
@O_ID INT NOT NULL,
@ORDER_NAME VARCHAR(25),
@ORDER_ADDRESS VARCHAR(45),
CHECK(@O_ID>2)
)
DEFAULT :-
We can provide default values to the table like in the above table :-
CREATE TABLE SHIP_ORDERS
(
@O_ID INT NOT NULL,
@ORDER_NAME VARCHAR(25) DEFAULT 'SLITTING',
@ORDER_ADDRESS VARCHAR(45) DEFAULT 'DELHI AIRPORT',
CHECK(@O_ID>2)
)
TO ALTER DEFAULT VALUE :-
ALTER TABLE SHIP_ORDERS
ALTER COLUMN @ORDER_NAME SET DEFAULT 'SPLIT'
TO DROP DEFAULT VALUES :-
ALTER TABLE SHIP_ORDERS
ALTER COLUMN @ORDER_NAME DROP DEFAULT
CREATE INDEX :-
CREATE INDEX index_name
ON table_name (column_name)
LIKE :-
CREATE INDEX index
ON SHIP_ORDERS (@ORDER_NAME,@ORDER_ADDRESS)
SQL Tools(Create DB, Create Table, UNION, UNION ALL, NOT NULL, UNIQUE, PRIMARY KEY, Foreign Key)
To Create Database :-
CREATE DATABASE Db_Name
To Create Table :-
CREATE TABLE Person
(
@ID INT NOT NULL,
@Name VARCHAR(20),
@ADDRESS VARCHAR(255) NOT NULL,
@PS_NO SMALLINT,
@FIRST_CHAR CHAR
)
if a column contains NOT NULL values then it means it does not allow the null values.
Unique :-
CREATE TABLE Person
(
@ID INT NOT NULL UNIQUE,
@Name VARCHAR(20),
@ADDRESS VARCHAR(255) NOT NULL,
@PS_NO SMALLINT,
@FIRST_CHAR CHAR
)
Another way to represent is and the way to define primary key :-
CREATE TABLE Person
(
@ID INT NOT NULL,
@Name VARCHAR(20),
@ADDRESS VARCHAR(255) NOT NULL,
@PS_NO SMALLINT,
@FIRST_CHAR CHAR,
UNIQUE(@ID),
PRIMARY KEY(@ID)
)
A primary key value can not have null values.
If more than one column has unique value then below way we will handle :-
UNIQUE(@ID, @ADDRESS)
FOREIGN KEY :-
If a table does not have primary key then it points to a primary key to another table then that key calls a foreign key for that table like :-
CREATE TABLE Person_Values
(
@P_ID INT NOT NULL,
@ID INT NOT NULL,
@P_Name VARCHAR(20),
@P_ADDRESS VARCHAR(255) NOT NULL,
@P_PS_NO SMALLINT,
@P_FIRST_CHAR CHAR,
FOREIGN KEY (@Id) REFERENCES Persons(@Id)
)
@ID is a primary key of Persons table and now working as a foreign key for Person_Values table.
UNION AND UNION ALL :-
Union will select the distinct values from both columns. In more general form Union with distinct values
Union All select all the values from selected columns.
UNION :-
SELECT column_name From table1
UNION
SELECT column_name From table2
UNION ALL :-
SELECT column_name From table1
UNION ALL
SELECT column_name From table2
CREATE DATABASE Db_Name
To Create Table :-
CREATE TABLE Person
(
@ID INT NOT NULL,
@Name VARCHAR(20),
@ADDRESS VARCHAR(255) NOT NULL,
@PS_NO SMALLINT,
@FIRST_CHAR CHAR
)
if a column contains NOT NULL values then it means it does not allow the null values.
Unique :-
CREATE TABLE Person
(
@ID INT NOT NULL UNIQUE,
@Name VARCHAR(20),
@ADDRESS VARCHAR(255) NOT NULL,
@PS_NO SMALLINT,
@FIRST_CHAR CHAR
)
Another way to represent is and the way to define primary key :-
CREATE TABLE Person
(
@ID INT NOT NULL,
@Name VARCHAR(20),
@ADDRESS VARCHAR(255) NOT NULL,
@PS_NO SMALLINT,
@FIRST_CHAR CHAR,
UNIQUE(@ID),
PRIMARY KEY(@ID)
)
A primary key value can not have null values.
If more than one column has unique value then below way we will handle :-
UNIQUE(@ID, @ADDRESS)
FOREIGN KEY :-
If a table does not have primary key then it points to a primary key to another table then that key calls a foreign key for that table like :-
CREATE TABLE Person_Values
(
@P_ID INT NOT NULL,
@ID INT NOT NULL,
@P_Name VARCHAR(20),
@P_ADDRESS VARCHAR(255) NOT NULL,
@P_PS_NO SMALLINT,
@P_FIRST_CHAR CHAR,
FOREIGN KEY (@Id) REFERENCES Persons(@Id)
)
@ID is a primary key of Persons table and now working as a foreign key for Person_Values table.
UNION AND UNION ALL :-
Union will select the distinct values from both columns. In more general form Union with distinct values
Union All select all the values from selected columns.
UNION :-
SELECT column_name From table1
UNION
SELECT column_name From table2
UNION ALL :-
SELECT column_name From table1
UNION ALL
SELECT column_name From table2
SQL Tools( Count, MAX, MIN)
COUNT is a method which will count the total no of columns,total no of rows,total no of values.Like :-
SELECT COUNT(Column_Name) FROM Table_Name
This will count total no of rows where First_Name is Saurabh.
SELECT Count(*) FROM Table_Name WHERE First_Name = 'Saurabh'
SELECT COUNT(First_Name) AS NoOfStudents FROM STUDENTS
STUDENTS is a Table_Name
Max :-
SELECT MAX(Column1) From Table1
SELECT MAX(DateOfBirth) AS BirthDate FROM Employee WHERE DateOfBirth > 12202009
Min :-
SELECT MIN(Column1) From Table1
SELECT MIN(DateOfBirth) AS BirthDate FROM Employee WHERE DateOfBirth < 12202009
SELECT COUNT(Column_Name) FROM Table_Name
This will count total no of rows where First_Name is Saurabh.
SELECT Count(*) FROM Table_Name WHERE First_Name = 'Saurabh'
SELECT COUNT(First_Name) AS NoOfStudents FROM STUDENTS
STUDENTS is a Table_Name
Max :-
SELECT MAX(Column1) From Table1
SELECT MAX(DateOfBirth) AS BirthDate FROM Employee WHERE DateOfBirth > 12202009
Min :-
SELECT MIN(Column1) From Table1
SELECT MIN(DateOfBirth) AS BirthDate FROM Employee WHERE DateOfBirth < 12202009
SQL Tools(SELECT INTO, INSERT INTO)
SQL SELECT INTO statement is used to select data from a SQL database table and to insert it to a different table at the same time.
The general SQL SELECT INTO syntax looks like this:
SELECT Column1, Column2, Column3,
INTO Table2 FROM Table1
This will create a Table2 same as Table1.
SQL INSERT INTO :-
1:- INSERT INTO Table1 VALUES (value1, value2, value3…)
2:- INSERT INTO Table1 (column1,column2,column3) VALUES(value1,value2,value3)
The general SQL SELECT INTO syntax looks like this:
SELECT Column1, Column2, Column3,
INTO Table2 FROM Table1
This will create a Table2 same as Table1.
SQL INSERT INTO :-
1:- INSERT INTO Table1 VALUES (value1, value2, value3…)
2:- INSERT INTO Table1 (column1,column2,column3) VALUES(value1,value2,value3)
SQL Tools(JOIN Operator(Inner join, Left join, Right join))
INNER JOIN Operator :-
INNER Join return all rows from the join of left table and right table if there are same data available in both tables if no data will match then it will return null
SELECT * FROM Table_Name_1 INNER JOIN Table_Name_2 WHERE Table_Name_1.Column_Name = Table_Name_2.Column_Name
You can divide your result in group like :-
If a table contains First_Name, Last_Name, Address, Ph_No and there are so many result according to First_Name then you can use Group_By Like this :-
SELECT * FROM Old_Persons As OP INNER JOIN New_Persons As NP WHERE OP.First_Name = NP.First_Name Group By OP.First_Name
LEFT JOIN Operator :-
LEFT join return all rows from the left table even there are no rows in right table.
SELECT * FROM Old_Persons As OP LEFT JOIN New_Persons As NP WHERE OP.First_Name = NP.First_Name Group By OP.First_Name
RIGHT JOIN Operator :-
RIGHT JOIN return all rows from the right table even if there are no rows available in left table.
SELECT * FROM Old_Persons As OP RIGHT JOIN New_Persons As NP WHERE OP.First_Name = NP.First_Name Group By OP.First_Name
INNER Join return all rows from the join of left table and right table if there are same data available in both tables if no data will match then it will return null
SELECT * FROM Table_Name_1 INNER JOIN Table_Name_2 WHERE Table_Name_1.Column_Name = Table_Name_2.Column_Name
You can divide your result in group like :-
If a table contains First_Name, Last_Name, Address, Ph_No and there are so many result according to First_Name then you can use Group_By Like this :-
SELECT * FROM Old_Persons As OP INNER JOIN New_Persons As NP WHERE OP.First_Name = NP.First_Name Group By OP.First_Name
LEFT JOIN Operator :-
LEFT join return all rows from the left table even there are no rows in right table.
SELECT * FROM Old_Persons As OP LEFT JOIN New_Persons As NP WHERE OP.First_Name = NP.First_Name Group By OP.First_Name
RIGHT JOIN Operator :-
RIGHT JOIN return all rows from the right table even if there are no rows available in left table.
SELECT * FROM Old_Persons As OP RIGHT JOIN New_Persons As NP WHERE OP.First_Name = NP.First_Name Group By OP.First_Name
SQL Tools(Alias Operator & In Operator)
ALIAS Name for Column :-
SELECT Column_Name AS Alias_Name FROM Table_Name
ALIAS Name for table :-
SELECT Column_Name From Table_Name AS Alias_Name
ALIAS Example :-
SELECT p.FirstName,p.LastName, po.OrderID
FROM Persons AS p, Product AS po
WHERE p.FirstName='Saurabh' AND p.LastName='Singh' AND po.OrderID > 2
Without using AS
SELECT p.FirstName,p.LastName, po.OrderID
FROM Persons p, Product po
WHERE p.FirstName='Saurabh' AND p.LastName='Singh' AND po.OrderID > 2
IN Operator :-
If you want to select OrderID of between 2,3,4,5 then :-
SELECT p.FirstName,p.LastName, po.OrderID
FROM Persons p, Product po
WHERE p.FirstName='Saurabh' AND p.LastName='Singh' AND po.OrderID IN (2,3,4,5)
OR :-
SELECT * FROM Persons
WHERE FirstName IN ('Saurabh','Saanjh', 'vivek')
SELECT Column_Name AS Alias_Name FROM Table_Name
ALIAS Name for table :-
SELECT Column_Name From Table_Name AS Alias_Name
ALIAS Example :-
SELECT p.FirstName,p.LastName, po.OrderID
FROM Persons AS p, Product AS po
WHERE p.FirstName='Saurabh' AND p.LastName='Singh' AND po.OrderID > 2
Without using AS
SELECT p.FirstName,p.LastName, po.OrderID
FROM Persons p, Product po
WHERE p.FirstName='Saurabh' AND p.LastName='Singh' AND po.OrderID > 2
IN Operator :-
If you want to select OrderID of between 2,3,4,5 then :-
SELECT p.FirstName,p.LastName, po.OrderID
FROM Persons p, Product po
WHERE p.FirstName='Saurabh' AND p.LastName='Singh' AND po.OrderID IN (2,3,4,5)
OR :-
SELECT * FROM Persons
WHERE FirstName IN ('Saurabh','Saanjh', 'vivek')
SQL - Tools (BETWEEN Operator)
SELECT column_name(s) FROM table_name
WHERE column_name BETWEEN value1 AND value2
SELECT * FROM COILS WHERE COIL_NAME BETWEEN SomeValue1 AND SomeValue2
Between operator is like It will select a row where COIL_NAME has SomeValue1 . Value depends on database to database . Some database will select rows where COIL_NAME has SomeValue1 and where COIL_NAME has SomeValue2.
We can use NOT BETWEEN operator if you you dont want to select those values like :-
SELECT * FROM COILS WHERE COIL_NAME NOT BETWEEN SomeValue1 AND SomeValue2
This query will select a value where coil_name is not equal to SomeValue1 and SomeValue2.
WHERE column_name BETWEEN value1 AND value2
SELECT * FROM COILS WHERE COIL_NAME BETWEEN SomeValue1 AND SomeValue2
Between operator is like It will select a row where COIL_NAME has SomeValue1 . Value depends on database to database . Some database will select rows where COIL_NAME has SomeValue1 and where COIL_NAME has SomeValue2.
We can use NOT BETWEEN operator if you you dont want to select those values like :-
SELECT * FROM COILS WHERE COIL_NAME NOT BETWEEN SomeValue1 AND SomeValue2
This query will select a value where coil_name is not equal to SomeValue1 and SomeValue2.
SQL - Tools(Top Clause AND Like Operator)
SELECT TOP 1 FROM Table_Name
This will select 1 row from table
SELECT TOP 1* FROM Table_Name (Select all columns of 1st row)
SELECT TOP 2* FROM Table_Name (Select first two rows of table)
SELECT TOP 50 PERCENT * FROM Table_Name (Select 50 % rows from table)
LIKE OPERATOR
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
IF a column name CITY from Persons table contains Kanpur, Delhi , NewDelhi , Kannauj , Nagar values then If you want to select city name starts from K then :-
SELECT * FROM Persons
WHERE CITY LIKE 'k%'
this will retrieve Kanpur , Kannauj.
If you want to select city name ends from i then :-
SELECT * FROM Persons
WHERE CITY LIKE '%i'
IF you want to select a city which has particular format like Select a city which has 'elh' pattern
SELECT * FROM Persons
WHERE City LIKE '%elh%'
this will retrieve Delhi , NewDelhi.
If you dont want to select a city which has particular format like 'elh'
SELECT * FROM Persons
WHERE City NOT LIKE '%elh%'
This will select 1 row from table
SELECT TOP 1* FROM Table_Name (Select all columns of 1st row)
SELECT TOP 2* FROM Table_Name (Select first two rows of table)
SELECT TOP 50 PERCENT * FROM Table_Name (Select 50 % rows from table)
LIKE OPERATOR
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
IF a column name CITY from Persons table contains Kanpur, Delhi , NewDelhi , Kannauj , Nagar values then If you want to select city name starts from K then :-
SELECT * FROM Persons
WHERE CITY LIKE 'k%'
this will retrieve Kanpur , Kannauj.
If you want to select city name ends from i then :-
SELECT * FROM Persons
WHERE CITY LIKE '%i'
IF you want to select a city which has particular format like Select a city which has 'elh' pattern
SELECT * FROM Persons
WHERE City LIKE '%elh%'
this will retrieve Delhi , NewDelhi.
If you dont want to select a city which has particular format like 'elh'
SELECT * FROM Persons
WHERE City NOT LIKE '%elh%'
SQL - Tools ( INSERT,UPDATE and DELETE Statement)
INSERT INTO table_name
VALUES (value1, value2, value3,...)
IF a table Persons contains P_Id,LastName,FirstName,Address,City columns.If you want to insert values then :-
INSERT INTO Persons
VALUES (4,'Singh', 'Saurabh', 'Sector-23', 'Gurgaon')
IF NOT EXISTS (SELECT * FROM Persons WHERE P_Id = 4)
BEGIN
INSERT INTO Persons
VALUES (4,'Singh', 'Saurabh', 'Sector-23', 'Gurgaon')
END
By this way it will check firstly, if this p_id exist in the table then do not insert otherwise insert these values in the table.
Update statement :-
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
We use If not exist statement whether there is a need to update or not.
DELETE Statement :-
DELETE From table_name WHERE some_column=some_value
Note :- Never use Delete * use Delete tableName.*
VALUES (value1, value2, value3,...)
IF a table Persons contains P_Id,LastName,FirstName,Address,City columns.If you want to insert values then :-
INSERT INTO Persons
VALUES (4,'Singh', 'Saurabh', 'Sector-23', 'Gurgaon')
IF NOT EXISTS (SELECT * FROM Persons WHERE P_Id = 4)
BEGIN
INSERT INTO Persons
VALUES (4,'Singh', 'Saurabh', 'Sector-23', 'Gurgaon')
END
By this way it will check firstly, if this p_id exist in the table then do not insert otherwise insert these values in the table.
Update statement :-
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
We use If not exist statement whether there is a need to update or not.
DELETE Statement :-
DELETE From table_name WHERE some_column=some_value
Note :- Never use Delete * use Delete tableName.*
SQL - Tools(ORDER BY)
ORDER BY keyword is used for sorting suppose in a table there is a column named first_name.
If you want to show the result in ascending order then :-
SELECT * FROM Persons WHERE Age >= 25 GROUP BY first_name ASC
If you want to show the result in descending order then :-
SELECT * FROM Persons WHERE Age >= 25 GROUP BY first_name DESC
By default it is ascendeng . if we use like GROUP BY first_name then it sorts in ascending order.
If you want to show the result in ascending order then :-
SELECT * FROM Persons WHERE Age >= 25 GROUP BY first_name ASC
If you want to show the result in descending order then :-
SELECT * FROM Persons WHERE Age >= 25 GROUP BY first_name DESC
By default it is ascendeng . if we use like GROUP BY first_name then it sorts in ascending order.
SQL - Tools (WHERE, AND, OR Clause)
Where clause is use for filtering like :-
SELECT * FROM table_name WHERE column_name (operator) value
(operator) :- =, >, <,! and more operators.
A Friends table contains firstName, secondName, address, phone_no and firstName values are :- saurabh, sandy, gaurav, somu, saurabh and address column values are :- kanpur, allahabad, delhi, kanpur, varanasi.
SELECT * FROM Friends WHERE firstName = 'Saurabh' AND address = 'kanpur'
This will select only first row because only first row satisfies WHERE condition
SELECT * FROM Friends WHERE firstName = 'Saurabh' OR address = 'kanpur'
This will select first row, fourth row and fifth row due to oR condition in where clause
Operators :-
< :- lessthan
> :- greaterthan
<= :- less than or equal to
>= :- greater than or equal to
<> :- not equal to
BETWEEN :- between an inclusive range
LIKE :- for search pattern
IN :- SEARCH for exact values like if i know values are 1987, 1989
Use of IN clause :-
EXAMPLE :- SELECT * FROM Friends WHERE year IN (1987, 1989)
SELECT * FROM table_name WHERE column_name (operator) value
(operator) :- =, >, <,! and more operators.
A Friends table contains firstName, secondName, address, phone_no and firstName values are :- saurabh, sandy, gaurav, somu, saurabh and address column values are :- kanpur, allahabad, delhi, kanpur, varanasi.
SELECT * FROM Friends WHERE firstName = 'Saurabh' AND address = 'kanpur'
This will select only first row because only first row satisfies WHERE condition
SELECT * FROM Friends WHERE firstName = 'Saurabh' OR address = 'kanpur'
This will select first row, fourth row and fifth row due to oR condition in where clause
Operators :-
< :- lessthan
> :- greaterthan
<= :- less than or equal to
>= :- greater than or equal to
<> :- not equal to
BETWEEN :- between an inclusive range
LIKE :- for search pattern
IN :- SEARCH for exact values like if i know values are 1987, 1989
Use of IN clause :-
EXAMPLE :- SELECT * FROM Friends WHERE year IN (1987, 1989)
SQL - Tools....(SELECT Clause)
SELECT :-
SELECT * FROM TABLE_NAME this will select whole table
If Coils table contains 5 columns p_id, coil_no, coil_width, coil_length, coil_name.Then you have to select coil_width and coil_no like :-
SELECT coil_width, coil_length FROM Coils
If you have to select distinct columns from table like coil_name columns have ABCDE12, ABCD13, ABCD14, ABCD12, ABCD14 then you have to choose only distinct values :-
SELECT DISTINCT column_name FROM table_name
SELECT DISTINCT coil_name FROM coils
SELECT * FROM TABLE_NAME this will select whole table
If Coils table contains 5 columns p_id, coil_no, coil_width, coil_length, coil_name.Then you have to select coil_width and coil_no like :-
SELECT coil_width, coil_length FROM Coils
If you have to select distinct columns from table like coil_name columns have ABCDE12, ABCD13, ABCD14, ABCD12, ABCD14 then you have to choose only distinct values :-
SELECT DISTINCT column_name FROM table_name
SELECT DISTINCT coil_name FROM coils
Visual Studio .Net ShortCut keys
DecreaseFilterLevel : ALT + ,
IncreaseFilterLevel : ALT + .
GotoBrace : CTRL + ]
GotoBraceExtend : CTRL _ SHIFT + ]
LineEnd : END
LineEndExtendColumn : SHIFT + ALT + END
ToggleWordWrap : CTRL + E, CTRL + W
ScrollLineDown : CTRL + DOWN ARRAY
LineDownExtendColumn : SHIFT + ALT + DOWN ARRAY
WordDeleteToEnd : CTRL + DEL
CopyParameterTip : CTRL + SHIFT + ALT + C
WordDeleteToStart : CTRL + BACKSPACE
SelectCurrentWord : CTRL + W
ViewWhiteSpace : CTRL + R , CTRL + W
Commenting : CTRL + k , CTRL + C
Uncommenting : CTRL + K , CTRL + U
IncreaseFilterLevel : ALT + .
GotoBrace : CTRL + ]
GotoBraceExtend : CTRL _ SHIFT + ]
LineEnd : END
LineEndExtendColumn : SHIFT + ALT + END
ToggleWordWrap : CTRL + E, CTRL + W
ScrollLineDown : CTRL + DOWN ARRAY
LineDownExtendColumn : SHIFT + ALT + DOWN ARRAY
WordDeleteToEnd : CTRL + DEL
CopyParameterTip : CTRL + SHIFT + ALT + C
WordDeleteToStart : CTRL + BACKSPACE
SelectCurrentWord : CTRL + W
ViewWhiteSpace : CTRL + R , CTRL + W
Commenting : CTRL + k , CTRL + C
Uncommenting : CTRL + K , CTRL + U
How to implement a progressBar while opening a textFile in an application ?
Make a claas like this one to create ProgressBar :-
public class StatusProgressBar : ToolStripProgressBar
{
#region Private Fields
private static StatusProgressBar _instance = null;
#endregion
#region Constructor
private StatusProgressBar()
{
this.Style = ProgressBarStyle.Blocks;
this.Step = 1;
}
#endregion
#region Properties
///
/// Get Singleton instance of progressBar
///
public static StatusProgressBar Instance
{
get
{
if (_instance == null)
{
_instance = new StatusProgressBar();
}
return _instance;
}
}
#endregion
}
Now main issue how to increase the bar and how calculate the percentage then firstly i would say calculate numer of lines to be read or parsed in amy editor according to your application
public const char NEWLINE_CHARACTER = '\n';
string[] lines = t.Split(NEWLINE_CHARACTER);
This will perform for all the lines and lines will be incremented then progress bar will be increemented accordingly.
for (int lineIndex = 0; lineIndex < lines.Length; lineIndex++)
{
if (lineIndex % 2 == 0)
{
StatusProgressBar.Instance.PerformStep();
StatusProgressBar.Instance.ToolTipText = Convert.ToString((StatusProgressBar.Instance.Value / StatusProgressBar.Instance.Maximum) * 100) + "%";
}
}
Happy to code................
public class StatusProgressBar : ToolStripProgressBar
{
#region Private Fields
private static StatusProgressBar _instance = null;
#endregion
#region Constructor
private StatusProgressBar()
{
this.Style = ProgressBarStyle.Blocks;
this.Step = 1;
}
#endregion
#region Properties
///
/// Get Singleton instance of progressBar
///
public static StatusProgressBar Instance
{
get
{
if (_instance == null)
{
_instance = new StatusProgressBar();
}
return _instance;
}
}
#endregion
}
Now main issue how to increase the bar and how calculate the percentage then firstly i would say calculate numer of lines to be read or parsed in amy editor according to your application
public const char NEWLINE_CHARACTER = '\n';
string[] lines = t.Split(NEWLINE_CHARACTER);
This will perform for all the lines and lines will be incremented then progress bar will be increemented accordingly.
for (int lineIndex = 0; lineIndex < lines.Length; lineIndex++)
{
if (lineIndex % 2 == 0)
{
StatusProgressBar.Instance.PerformStep();
StatusProgressBar.Instance.ToolTipText = Convert.ToString((StatusProgressBar.Instance.Value / StatusProgressBar.Instance.Maximum) * 100) + "%";
}
}
Happy to code................
What is Reference counting in COM ?
Reference counting is a memory management technique used to count how many times an object has a pointer referring to it. The first time it is created, the reference count is set to one. When the last reference to the object is nulled, the reference count is set to zero and the object is deleted.
Care must be exercised to prevent a context switch from changing the reference count at the time of deletion. In the methods that follow, the syntax is shortened to keep the scope of the discussion brief and manageable.
Care must be exercised to prevent a context switch from changing the reference count at the time of deletion. In the methods that follow, the syntax is shortened to keep the scope of the discussion brief and manageable.
What is COM ?
Microsoft’s COM is a technology for component software development. It is a binary standard which is language independent. DCOM is a distributed extension of COM.
Microsoft COM (Component Object Model) technology in the Microsoft Windows-family of Operating Systems enables software components to communicate. COM is used by developers to create re-usable software components, link components together to build applications, and take advantage of Windows services. COM objects can be created with a variety of programming languages. Object-oriented languages, such as C++, provide programming mechanisms that simplify the implementation of COM objects. The family of COM technologies includes COM+, Distributed COM (DCOM) and ActiveX® Controls.
Microsoft provides COM interfaces for many Windows application programming interfaces such as Direct Show, Media Foundation, Packaging API, Windows Animation Manager, Windows Portable Devices, and Microsoft Active Directory (AD).
COM is used in applications such as the Microsoft Office Family of products. For example COM OLE technology allows Word documents to dynamically link to data in Excel spreadsheets and COM Automation allows users to build scripts in their applications to perform repetitive tasks or control one application from another.
Microsoft COM (Component Object Model) technology in the Microsoft Windows-family of Operating Systems enables software components to communicate. COM is used by developers to create re-usable software components, link components together to build applications, and take advantage of Windows services. COM objects can be created with a variety of programming languages. Object-oriented languages, such as C++, provide programming mechanisms that simplify the implementation of COM objects. The family of COM technologies includes COM+, Distributed COM (DCOM) and ActiveX® Controls.
Microsoft provides COM interfaces for many Windows application programming interfaces such as Direct Show, Media Foundation, Packaging API, Windows Animation Manager, Windows Portable Devices, and Microsoft Active Directory (AD).
COM is used in applications such as the Microsoft Office Family of products. For example COM OLE technology allows Word documents to dynamically link to data in Excel spreadsheets and COM Automation allows users to build scripts in their applications to perform repetitive tasks or control one application from another.
How can we make Windows API calls in .NET?
Windows API call are not COM based and they are invoked through Platform Invoke Services.StringConversionType is for what type of conversion should take place. Either we can specify Unicode to convert all strings to Unicode values, or Auto to convert strings according to the .NET runtime rules.
There are few thumbrules to make API calls :-
1:- MethodName is the name of the API to call.
2:- DllName is the name of the DLL.
3:- Args are any arguments to the API call.
4:- Type is the return type of the API call.
partial class Form1 : Form
{
[DllImport(“Kernel32.dll”)]
static extern int Sleep(long dwMilliseconds);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show(“Starting of 5000 ms...”);
Sleep(5000);
MessageBox.Show(“End of 5000 ms...”);
}
}
}
There are few thumbrules to make API calls :-
1:- MethodName is the name of the API to call.
2:- DllName is the name of the DLL.
3:- Args are any arguments to the API call.
4:- Type is the return type of the API call.
partial class Form1 : Form
{
[DllImport(“Kernel32.dll”)]
static extern int Sleep(long dwMilliseconds);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show(“Starting of 5000 ms...”);
Sleep(5000);
MessageBox.Show(“End of 5000 ms...”);
}
}
}
ShFileOperation not working under Wista and Windows7.
I've used ShFileOperation for file operations but was facing some problems and i was not able to understand then i do googling and found the 'cause' of the problems with the SHFileOperation function in Vista . It turns out that this function is not thread safe under Vista. It works fine with earlier operating systems when used in a multi threading application.
Then i got to know about IFileOPeration interface in vista, you can say a replacement of ShFileOperation.
Then i got to know about IFileOPeration interface in vista, you can say a replacement of ShFileOperation.
How to convert 2d array to 1d array ?
Suppose you to insert or get the values from 1d array using 2d dimensions like :-
Insert value at (1,2) and the value is 5 then you have to find the logic to get the index :-
Firstly you have to know the size of 2d array here suppose :- (2x3)
int xPosition = 1;
int yPosition = 2;
3 is ySize of 2d array.
int 1dIndex = (3*xPosition)+ yPosition ;
Insert at this index or get from this index.
Insert value at (1,2) and the value is 5 then you have to find the logic to get the index :-
Firstly you have to know the size of 2d array here suppose :- (2x3)
int xPosition = 1;
int yPosition = 2;
3 is ySize of 2d array.
int 1dIndex = (3*xPosition)+ yPosition ;
Insert at this index or get from this index.
How to convert 3d array to 1d array ?
Suppose you have to insert a value at (2,1,0) and the value is :-5
means firstly you have to find the index through (2,1,0) then you have to insert value 5 at that index .
Logic is :-
Firstly you must have to know the 3d array size suppose here is (3x2x3).
int xPosition = 2;
int yPosition = 1;
int zPosition = 0;
int indexOf1dArray = (xPosition *2*3) + ((yPosition * 3)+zPosition) ;
Using this insert the value at this index indexOf1dArray and if you have to get the value then again find index using this method and then find the value at this place.
means firstly you have to find the index through (2,1,0) then you have to insert value 5 at that index .
Logic is :-
Firstly you must have to know the 3d array size suppose here is (3x2x3).
int xPosition = 2;
int yPosition = 1;
int zPosition = 0;
int indexOf1dArray = (xPosition *2*3) + ((yPosition * 3)+zPosition) ;
Using this insert the value at this index indexOf1dArray and if you have to get the value then again find index using this method and then find the value at this place.
What is the difference between .ToString() and Convert.ToString() ?
int value = 3;
string stringConversion = value.ToString();
string stringConversion = Convert.ToString(value);
We can convert the integer “value ” using “value .ToString()” or “Convert.ToString”
The basic difference between them is “Convert” function handles NULLS .It handles null exception while “value .ToString()”does not it will throw a NULL reference exception error. So as good coding practice using “convert” is always safe.
Happy to code...
string stringConversion = value.ToString();
string stringConversion = Convert.ToString(value);
We can convert the integer “value ” using “value .ToString()” or “Convert.ToString”
The basic difference between them is “Convert” function handles NULLS .It handles null exception while “value .ToString()”does not it will throw a NULL reference exception error. So as good coding practice using “convert” is always safe.
Happy to code...
Built-in Code Snippets (C#)
List of built in code snippets -
#if :- Creates a #if directive and a #endif directive.
#region :- Creates a #region directive and a #endregion directive.
~ :- Creates a destructor for the containing class.
checked :- Creates a checked block.
ctor :- Creates a constructor for the containing class.
cw :- Creates a call to Console.WriteLine.
for :- Creates a for loop.
forr :- Creates a for loop that decrements the loop variable after each iteration.
invoke :- Creates a block that safely invokes an event.
iterindex :- Creates a "named" iterator and indexer pair by using a nested class.
lock :- Creates a lock block.
mbox :- Creates a call to System.Windows.Forms.MessageBox.Show. You
may need to add a reference to System.Windows.Forms.dll.
prop :- Creates a automatic property
propg :- Creates a property declaration with only a "get" accessor and a backing field.
propfull : Creates a property with private field.
sim :- Creates a static int Main method declaration.
svm :- Creates a static void Main method declaration.
try :- Creates a try-catch block.
tryf :- Creates a try-finally block.
unsafe :- Creates an unsafe block.
unchecked :- Creates an unchecked block.
Happy to code.
#if :- Creates a #if directive and a #endif directive.
#region :- Creates a #region directive and a #endregion directive.
~ :- Creates a destructor for the containing class.
checked :- Creates a checked block.
ctor :- Creates a constructor for the containing class.
cw :- Creates a call to Console.WriteLine.
for :- Creates a for loop.
forr :- Creates a for loop that decrements the loop variable after each iteration.
invoke :- Creates a block that safely invokes an event.
iterindex :- Creates a "named" iterator and indexer pair by using a nested class.
lock :- Creates a lock block.
mbox :- Creates a call to System.Windows.Forms.MessageBox.Show. You
may need to add a reference to System.Windows.Forms.dll.
prop :- Creates a automatic property
propg :- Creates a property declaration with only a "get" accessor and a backing field.
propfull : Creates a property with private field.
sim :- Creates a static int Main method declaration.
svm :- Creates a static void Main method declaration.
try :- Creates a try-catch block.
tryf :- Creates a try-finally block.
unsafe :- Creates an unsafe block.
unchecked :- Creates an unchecked block.
Happy to code.
Message-Box refreshing issue
I have used many message boxes in my current application but in some places where i used list box,list there when i move messagebox then the back screen is looks like everything is removing or cleaning nothing just refreshing issue, then i look and sort out by sinety testing like i used listView.BeginUpdate(); before dialog box check when i used after it then it works fine. because this method is used to update listview without any flicker and refreshing but i used before dialog check thats why i was facing that problem.
Happy to code...
Happy to code...
How to collapse Environmental variables in a path using C# ?
Pass the path if there are environmental variables exist in the path then it will be collapsed into a valid path and return the valid path.
Constants :-
public const string PATH_SEPARATOR = @"\";
public const string ENVIROMENT_VARIABLE_FORMAT = "%{0}%";
public static string CollapseEnviromentVariables(string pathString)
{
string result = pathString;
if (string.IsNullOrEmpty(pathString) == false)
{
IDictionary environmentVariables = Environment.GetEnvironmentVariables();
Dictionary matchingEnv = new Dictionary();
bool isReplaceEnv = false;
foreach (DictionaryEntry environmentVariable in environmentVariables)
{
if ((pathString.Length >= ((string)environmentVariable.Value).Length) && (pathString.Contains((string)environmentVariable.Value)))
{
isReplaceEnv = false;
foreach (string matchingEnvEntry in matchingEnv.Keys)
{
if ((((string)matchingEnv[matchingEnvEntry]).Length <= ((string)environmentVariable.Value).Length) &&
((string)environmentVariable.Value).Contains((string)matchingEnv[matchingEnvEntry]))
{
matchingEnv.Remove(matchingEnvEntry);
matchingEnv.Add((string)environmentVariable.Key, (string)environmentVariable.Value);
isReplaceEnv = true;
break;
}
}
if (isReplaceEnv == false)
{
matchingEnv.Add((string)environmentVariable.Key, (string)environmentVariable.Value);
}
}
}
int matchingEnvIndex = 0;
int matchingEnvLength = 0;
foreach (string matchingEnvEntry in matchingEnv.Keys)
{
matchingEnvIndex = result.IndexOf(matchingEnv[matchingEnvEntry]);
matchingEnvLength = matchingEnv[matchingEnvEntry].Length;
//Replace environment variable only if environment variable value is enclosed by path seperators
//and matched value is found after replacing other variables.
if ((matchingEnvIndex > -1) &&
((matchingEnvIndex == 0) || (result[matchingEnvIndex - 1].ToString() == Constants.PATH_SEPARATOR)) &&
((matchingEnvIndex + matchingEnvLength == result.Length) || (result[matchingEnvIndex + matchingEnvLength].ToString() == Constants.PATH_SEPARATOR)))
{
result = result.Replace(matchingEnv[matchingEnvEntry], string.Format(Constants.ENVIROMENT_VARIABLE_FORMAT, matchingEnvEntry));
}
}
}
return result;
}
Constants :-
public const string PATH_SEPARATOR = @"\";
public const string ENVIROMENT_VARIABLE_FORMAT = "%{0}%";
public static string CollapseEnviromentVariables(string pathString)
{
string result = pathString;
if (string.IsNullOrEmpty(pathString) == false)
{
IDictionary environmentVariables = Environment.GetEnvironmentVariables();
Dictionary
bool isReplaceEnv = false;
foreach (DictionaryEntry environmentVariable in environmentVariables)
{
if ((pathString.Length >= ((string)environmentVariable.Value).Length) && (pathString.Contains((string)environmentVariable.Value)))
{
isReplaceEnv = false;
foreach (string matchingEnvEntry in matchingEnv.Keys)
{
if ((((string)matchingEnv[matchingEnvEntry]).Length <= ((string)environmentVariable.Value).Length) &&
((string)environmentVariable.Value).Contains((string)matchingEnv[matchingEnvEntry]))
{
matchingEnv.Remove(matchingEnvEntry);
matchingEnv.Add((string)environmentVariable.Key, (string)environmentVariable.Value);
isReplaceEnv = true;
break;
}
}
if (isReplaceEnv == false)
{
matchingEnv.Add((string)environmentVariable.Key, (string)environmentVariable.Value);
}
}
}
int matchingEnvIndex = 0;
int matchingEnvLength = 0;
foreach (string matchingEnvEntry in matchingEnv.Keys)
{
matchingEnvIndex = result.IndexOf(matchingEnv[matchingEnvEntry]);
matchingEnvLength = matchingEnv[matchingEnvEntry].Length;
//Replace environment variable only if environment variable value is enclosed by path seperators
//and matched value is found after replacing other variables.
if ((matchingEnvIndex > -1) &&
((matchingEnvIndex == 0) || (result[matchingEnvIndex - 1].ToString() == Constants.PATH_SEPARATOR)) &&
((matchingEnvIndex + matchingEnvLength == result.Length) || (result[matchingEnvIndex + matchingEnvLength].ToString() == Constants.PATH_SEPARATOR)))
{
result = result.Replace(matchingEnv[matchingEnvEntry], string.Format(Constants.ENVIROMENT_VARIABLE_FORMAT, matchingEnvEntry));
}
}
}
return result;
}
How to allign multiple strings using seperator in C# ?
Constant file.public const char SYMBOL_SPACE_CHARACTER = ' ';
public static List AlignText(string[] strings, char seperator)
{
List formattedStringList = new List();
List ListOfCommaSeperatedStringsInLine = new List();
string[] commaSeperatedStringsArray = null;
List maxColumnWidthArray = new List();
//split strings into list of comma seperated array of strings and calculate maximum length of string array.
foreach (string str in strings)
{
commaSeperatedStringsArray = str.Split(seperator);
//remove all trailing and leading spaces.
for (int index = 0; index < commaSeperatedStringsArray.Length; ++index)
{
commaSeperatedStringsArray[index] = commaSeperatedStringsArray[index].Trim();
//initialize maximum characters in each column.
if (maxColumnWidthArray.Count > index)
{
maxColumnWidthArray[index] = (maxColumnWidthArray[index] < commaSeperatedStringsArray[index].Length) ? commaSeperatedStringsArray[index].Length : maxColumnWidthArray[index];
}
else
{
maxColumnWidthArray.Add(commaSeperatedStringsArray[index].Length);
}
}
ListOfCommaSeperatedStringsInLine.Add(commaSeperatedStringsArray);
}
StringBuilder formattedString = new StringBuilder();
int accumlativeMaxLength = 0;
int pad = 0;
//Insert spaces to align text and append in single line text.
foreach (string[] stringsInLine in ListOfCommaSeperatedStringsInLine)
{
formattedString.Append(stringsInLine[0]);
accumlativeMaxLength = maxColumnWidthArray[0];
for (int index = 1; index < maxColumnWidthArray.Count; ++index)
{
if (stringsInLine.Length > index)
{
pad = accumlativeMaxLength - formattedString.Length;
formattedString.Append(seperator);
formattedString.Append(Constants.SYMBOL_SPACE_CHARACTER, pad);
if (IsNumeric(stringsInLine[index]))
{
formattedString.Append(Constants.SYMBOL_SPACE_CHARACTER, maxColumnWidthArray[index] - stringsInLine[index].Length);
}
formattedString.Append(stringsInLine[index]);
accumlativeMaxLength += maxColumnWidthArray[index] + 1;
}
}
formattedStringList.Add(formattedString.ToString());
formattedString.Length = 0;
}
return formattedStringList;
}
This is very useful method when you have to align certain strings and there is a seperator then this method will allign all the lines, just pass the array of strings and a seperator.
public static List
{
List
List
string[] commaSeperatedStringsArray = null;
List
//split strings into list of comma seperated array of strings and calculate maximum length of string array.
foreach (string str in strings)
{
commaSeperatedStringsArray = str.Split(seperator);
//remove all trailing and leading spaces.
for (int index = 0; index < commaSeperatedStringsArray.Length; ++index)
{
commaSeperatedStringsArray[index] = commaSeperatedStringsArray[index].Trim();
//initialize maximum characters in each column.
if (maxColumnWidthArray.Count > index)
{
maxColumnWidthArray[index] = (maxColumnWidthArray[index] < commaSeperatedStringsArray[index].Length) ? commaSeperatedStringsArray[index].Length : maxColumnWidthArray[index];
}
else
{
maxColumnWidthArray.Add(commaSeperatedStringsArray[index].Length);
}
}
ListOfCommaSeperatedStringsInLine.Add(commaSeperatedStringsArray);
}
StringBuilder formattedString = new StringBuilder();
int accumlativeMaxLength = 0;
int pad = 0;
//Insert spaces to align text and append in single line text.
foreach (string[] stringsInLine in ListOfCommaSeperatedStringsInLine)
{
formattedString.Append(stringsInLine[0]);
accumlativeMaxLength = maxColumnWidthArray[0];
for (int index = 1; index < maxColumnWidthArray.Count; ++index)
{
if (stringsInLine.Length > index)
{
pad = accumlativeMaxLength - formattedString.Length;
formattedString.Append(seperator);
formattedString.Append(Constants.SYMBOL_SPACE_CHARACTER, pad);
if (IsNumeric(stringsInLine[index]))
{
formattedString.Append(Constants.SYMBOL_SPACE_CHARACTER, maxColumnWidthArray[index] - stringsInLine[index].Length);
}
formattedString.Append(stringsInLine[index]);
accumlativeMaxLength += maxColumnWidthArray[index] + 1;
}
}
formattedStringList.Add(formattedString.ToString());
formattedString.Length = 0;
}
return formattedStringList;
}
This is very useful method when you have to align certain strings and there is a seperator then this method will allign all the lines, just pass the array of strings and a seperator.
How to check invalid characters in path using C#
If you create a new folder then there are some characters which are not allowed and any thing in which user have rights to create path then firstly check the invalid characters otherwise your application or program will through an exception.
Pass the path or string for which you have to check.
public static bool CheckInvalidCharacters(string path)
{
bool invalidCharacters = false;
if (string.IsNullOrEmpty(path) == false)
{
char[] invalidChars = Path.GetInvalidFileNameChars();
foreach (char invalidChar in invalidChars)
{
if (path.Contains(invalidChar.ToString()))
{
invalidCharacters = true;
break;
}
}
}
return invalidCharacters;
}
This will return a bool variable if path or string contains invalid characters then it will return true else false.
Pass the path or string for which you have to check.
public static bool CheckInvalidCharacters(string path)
{
bool invalidCharacters = false;
if (string.IsNullOrEmpty(path) == false)
{
char[] invalidChars = Path.GetInvalidFileNameChars();
foreach (char invalidChar in invalidChars)
{
if (path.Contains(invalidChar.ToString()))
{
invalidCharacters = true;
break;
}
}
}
return invalidCharacters;
}
This will return a bool variable if path or string contains invalid characters then it will return true else false.
Delegates in C#
Event - Delegates are the key feature of C#,You can say heart of C#.Look on a example :- Suppose if you have two forms and there is no communication between those even you can't create object to access then how will you send some information.In this tutorial i will teach you how to handle and play with delegates to proper communication.
Suppose you have to pass the multiple file paths to different forms and they are in different solutions or different forms :-
Step.1 :-
Make a class which will contain all the file path like this :-
public class FileOpenEventArgs : EventArgs
{
#region Private Fields
private string [] _filePath;
#endregion
#region properties
///
/// Sets/Gets the path of files.
///
public string [] FilePath
{
get
{
return _filePath;
}
set
{
_filePath = value;
}
}
#endregion
}
step.2 :- Now come to form from you have to pass the information
Declare a delegate and event like :-
public delegate void FileOpenHandler(object sender, FileOpenEventArgs e);
public event FileOpenHandler FileOpen;
step.3 :- Now do the operation suppose you have to send the file name on drag-drop or on a mouse click or on mouse hover any event then create the object of the class and set the file names and then pass like in this way :-
I have used on drag-drop so get the file names in this way :-
string[] files = (string[])drgevent.Data.GetData(DataFormats.FileDrop);
or you can do other way to get the file names.
Create the object and set the file names.
FileOpenEventArgs fileOpen = new FileOpenEventArgs();
fileOpen.FilePath = files;
OnFilesOpen(this, fileOpen);
Handles FileOpen event.
protected void OnFilesOpen(object sender, FileOpenEventArgs e)
{
if (FileOpen != null)
{
FileOpen(this, e);
}
}
Step.4 :- Now handle your event on the form where you can create the object of this form or you can handle the event here too but I handled the event on onother solution like :-
private solution.explorer lightView;
then again create delegate and event like:-
public delegate void FileOpenHandler(object sender, FileDataOpenEventArgs e);
public event FileOpenHandler FileOpen;
Now handles the event :-
lightView.FileOpen += new solution.explorer.FileOpenHandler(lightView_FileOpen);
void lightView_FileOpen(object sender, FileOpenEventArgs e)
{
string [] fileData = e.FilePath;
FileDataOpenEventArgs fileDataOpenEventArgs = new FileDataOpenEventArgs(fileData);
OnFilesOpen(fileDataOpenEventArgs);
}
Handle protected method :-
protected void OnFilesOpen(FileDataOpenEventArgs e)
{
if (FileOpen != null)
{
FileOpen(this, e);
}
}
now create the event where you have to open or do something for files :-
create the instance of above class where you handle your event.
private lightView_lightViewPanel = new lightView();
_lightViewPanel.FileOpen += new lightView.FileOpenHandler(_lightViewPanel_FileOpen);
private void _lightViewPanel_FileOpen(object sender, FileDataOpenEventArgs e)
{
if (e != null)
{
now play with your path accesss e.FilePath property of this event you will get path.
}
}
Happy to code.
Suppose you have to pass the multiple file paths to different forms and they are in different solutions or different forms :-
Step.1 :-
Make a class which will contain all the file path like this :-
public class FileOpenEventArgs : EventArgs
{
#region Private Fields
private string [] _filePath;
#endregion
#region properties
///
/// Sets/Gets the path of files.
///
public string [] FilePath
{
get
{
return _filePath;
}
set
{
_filePath = value;
}
}
#endregion
}
step.2 :- Now come to form from you have to pass the information
Declare a delegate and event like :-
public delegate void FileOpenHandler(object sender, FileOpenEventArgs e);
public event FileOpenHandler FileOpen;
step.3 :- Now do the operation suppose you have to send the file name on drag-drop or on a mouse click or on mouse hover any event then create the object of the class and set the file names and then pass like in this way :-
I have used on drag-drop so get the file names in this way :-
string[] files = (string[])drgevent.Data.GetData(DataFormats.FileDrop);
or you can do other way to get the file names.
Create the object and set the file names.
FileOpenEventArgs fileOpen = new FileOpenEventArgs();
fileOpen.FilePath = files;
OnFilesOpen(this, fileOpen);
Handles FileOpen event.
protected void OnFilesOpen(object sender, FileOpenEventArgs e)
{
if (FileOpen != null)
{
FileOpen(this, e);
}
}
Step.4 :- Now handle your event on the form where you can create the object of this form or you can handle the event here too but I handled the event on onother solution like :-
private solution.explorer lightView;
then again create delegate and event like:-
public delegate void FileOpenHandler(object sender, FileDataOpenEventArgs e);
public event FileOpenHandler FileOpen;
Now handles the event :-
lightView.FileOpen += new solution.explorer.FileOpenHandler(lightView_FileOpen);
void lightView_FileOpen(object sender, FileOpenEventArgs e)
{
string [] fileData = e.FilePath;
FileDataOpenEventArgs fileDataOpenEventArgs = new FileDataOpenEventArgs(fileData);
OnFilesOpen(fileDataOpenEventArgs);
}
Handle protected method :-
protected void OnFilesOpen(FileDataOpenEventArgs e)
{
if (FileOpen != null)
{
FileOpen(this, e);
}
}
now create the event where you have to open or do something for files :-
create the instance of above class where you handle your event.
private lightView_lightViewPanel = new lightView();
_lightViewPanel.FileOpen += new lightView.FileOpenHandler(_lightViewPanel_FileOpen);
private void _lightViewPanel_FileOpen(object sender, FileDataOpenEventArgs e)
{
if (e != null)
{
now play with your path accesss e.FilePath property of this event you will get path.
}
}
Happy to code.
Generics in C#
Hi everyone..in .net 2.0 we do programming in a very smarter way Generics is the example like if we are using minimum finction to find minimum between two numbers they may be integer,string,object and may be some other data types.
Consider the following code :-
Returns minimum between two integers.
int Min( int a, int b )
{
if (a < b) return a;
else return b;
}
let suppose you have objects or string then this will not work.To use this code, we need a different version of Min for each type of parameter we want to compare then developers think to use in the folllowing manner :-
Returns minimum between two objects.
object Min( object a, object b )
{
if (a < b) return a;
else return b;
}
But less than operator (<) is not defined for the generic object type.So we need to use a coomon interface to use ex:-Icomparable. like in the following manner :-
IComparable Min( IComparable a, IComparable b )
{
if (a.CompareTo( b ) < 0) return a;
else return b;
}
By this way problem has been solved but now there is a big issue.A caller of Min that passes two integers should make a type conversion from IComparable to int and may be it gives an exception. like :-
int a = 7, b = 16
int c = (int) Min( a, b );
but .net 2.0 solved the issue using Generics.
This is the generic version of MIN method.
T Min( T a, T b ) where T : IComparable
{
if (a.CompareTo( b ) < 0) return a;
else return b;
}
Now you can call like in this manner :-
int a = 7 b = 16;
int c = Min( a, b );
Happy to code.
Consider the following code :-
Returns minimum between two integers.
int Min( int a, int b )
{
if (a < b) return a;
else return b;
}
let suppose you have objects or string then this will not work.To use this code, we need a different version of Min for each type of parameter we want to compare then developers think to use in the folllowing manner :-
Returns minimum between two objects.
object Min( object a, object b )
{
if (a < b) return a;
else return b;
}
But less than operator (<) is not defined for the generic object type.So we need to use a coomon interface to use ex:-Icomparable. like in the following manner :-
IComparable Min( IComparable a, IComparable b )
{
if (a.CompareTo( b ) < 0) return a;
else return b;
}
By this way problem has been solved but now there is a big issue.A caller of Min that passes two integers should make a type conversion from IComparable to int and may be it gives an exception. like :-
int a = 7, b = 16
int c = (int) Min( a, b );
but .net 2.0 solved the issue using Generics.
This is the generic version of MIN method.
T Min
{
if (a.CompareTo( b ) < 0) return a;
else return b;
}
Now you can call like in this manner :-
int a = 7 b = 16;
int c = Min
Happy to code.
Singleton Pattern
Singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is very useful when only there is a need of single object which handles all the actions across the system.This pattern restrict the instantiation to a certain number of objects and this concept is to generalize the systems to operate more efficiently when only one object exists.
Example :-
The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation
Implementation of Singleton pattern :-
///
/// Thread-safe singleton example without using locks
///
public sealed class SingletonClass
{
private static readonly SingletonClass singletonInstance = new SingletonClass();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static SingletonClass()
{
}
private SingletonClass()
{
}
///
/// The public Instance property to use
///
public static SingletonClass SingletonInstance
{
get { return singletonInstance ; }
}
}
Happy to code...
Hiii...One more example to clear singleton approach :-
I have implement progress bar for ma current application so i am giving some reference here:-
#region Private Fields
private static StatusProgressBar _instance = null;
#endregion
#region Constructor
private StatusProgressBar()
{
this.Style = ProgressBarStyle.Blocks;
this.Step = 1;
}
#endregion
#region Properties
///
/// Get Singleton instance of progressBar
///
public static StatusProgressBar Instance
{
get
{
if (_instance == null)
{
_instance = new StatusProgressBar();
}
return _instance;
}
}
#endregion
Made the above class as public and access it suppose class name is StatusProgressBar
StatusProgressBar.Instance.PerformStep();
then if instance is already running then it will return that instance otherwise will return a new instance.
Example :-
The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation
Implementation of Singleton pattern :-
///
/// Thread-safe singleton example without using locks
///
public sealed class SingletonClass
{
private static readonly SingletonClass singletonInstance = new SingletonClass();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static SingletonClass()
{
}
private SingletonClass()
{
}
///
/// The public Instance property to use
///
public static SingletonClass SingletonInstance
{
get { return singletonInstance ; }
}
}
Happy to code...
Hiii...One more example to clear singleton approach :-
I have implement progress bar for ma current application so i am giving some reference here:-
#region Private Fields
private static StatusProgressBar _instance = null;
#endregion
#region Constructor
private StatusProgressBar()
{
this.Style = ProgressBarStyle.Blocks;
this.Step = 1;
}
#endregion
#region Properties
///
/// Get Singleton instance of progressBar
///
public static StatusProgressBar Instance
{
get
{
if (_instance == null)
{
_instance = new StatusProgressBar();
}
return _instance;
}
}
#endregion
Made the above class as public and access it suppose class name is StatusProgressBar
StatusProgressBar.Instance.PerformStep();
then if instance is already running then it will return that instance otherwise will return a new instance.
What is LINQ?
■ LINQ is a uniform programming model for any kind of data. LINQ enables you to query
and manipulate data with a consistent model that is independent from data sources.
■ LINQ is just another tool for embedding SQL queries into code.
■ LINQ is yet another data abstraction layer.
and manipulate data with a consistent model that is independent from data sources.
■ LINQ is just another tool for embedding SQL queries into code.
■ LINQ is yet another data abstraction layer.
Remove special characters from string ?
public override string ToString()
{
string specialCharacters = "~!@#$%^&*<()+=`',.?>/\\\"";
string[] stringAfterRemovingSpecialCharacters= displayText.Split(specialCharacters .ToCharArray());
return string.Concat(stringAfterRemovingSpecialCharacters);
}
{
string specialCharacters = "~!@#$%^&*<()+=`',.?>/\\\"";
string[] stringAfterRemovingSpecialCharacters= displayText.Split(specialCharacters .ToCharArray());
return string.Concat(stringAfterRemovingSpecialCharacters);
}
File/Folder is being used by another process Error?
Hi Friends..
Resolved Error - File/Folder is being used by another process
As i discussed in my current project i made a self explorer.exe so i accessed all the folders,files .i am doing same behaviour as lioke window explorer.exe. But I was facing a error This file/folder is being used by another process and all that and i face all these errors when i rename,delete,move,copy,drag-drop.
Solution :- I add folders runtime and updation is all as real time.so I used shell com object and make tree using shell namespace like :-
node is treeNode of tree.
Shell32.FolderItem folderItem = (Shell32.FolderItem)node.Tag.FolderItem;
Shell32.Folder folder = (Shell32.Folder)folderItem.GetFolder;
then iterate thorugh foreach and used break statement because i add a dummynode in each node who have folders and when i expand that node then delete the dummynode and create the nodes for that treenode beacuase of efficiency.So on creating dummyNode i used foreach statement like :-
bool hasFolders = false;
foreach (Shell32.FolderItem item in folder.Items())
{
if (item.IsFileSystem && item.IsFolder && !item.IsBrowsable)
{
hasFolders = true;
break;
}
}
if (hasFolders)
{
TreeNode newTreeNode = new TreeNode();
newTreeNode.Tag = STRING_DUMMY_TREENODE;
treeNode.Nodes.Add(newTreeNode);
}
so this foreach actually its an iterator so when i use break statement so tis break from the loop but still it holds the object and shell thinks its used by some other program and all so dont use foreach if you using break statement like this :-
Shell32.FolderItems items = folder.Items();
for (int itemIndex = 0; itemIndex < items.Count; itemIndex++)
{
Shell32.FolderItem item = items.Item(itemIndex);
if (item.IsFileSystem && item.IsFolder && !item.IsBrowsable)
{
hasFolders = true;
break;
}
}
and now as above you will never face the error like file/folder is being used by another process so in your application if you are facing then firstly check it out and make sure you are not using any iterator.
Happy to code.
Resolved Error - File/Folder is being used by another process
As i discussed in my current project i made a self explorer.exe so i accessed all the folders,files .i am doing same behaviour as lioke window explorer.exe. But I was facing a error This file/folder is being used by another process and all that and i face all these errors when i rename,delete,move,copy,drag-drop.
Solution :- I add folders runtime and updation is all as real time.so I used shell com object and make tree using shell namespace like :-
node is treeNode of tree.
Shell32.FolderItem folderItem = (Shell32.FolderItem)node.Tag.FolderItem;
Shell32.Folder folder = (Shell32.Folder)folderItem.GetFolder;
then iterate thorugh foreach and used break statement because i add a dummynode in each node who have folders and when i expand that node then delete the dummynode and create the nodes for that treenode beacuase of efficiency.So on creating dummyNode i used foreach statement like :-
bool hasFolders = false;
foreach (Shell32.FolderItem item in folder.Items())
{
if (item.IsFileSystem && item.IsFolder && !item.IsBrowsable)
{
hasFolders = true;
break;
}
}
if (hasFolders)
{
TreeNode newTreeNode = new TreeNode();
newTreeNode.Tag = STRING_DUMMY_TREENODE;
treeNode.Nodes.Add(newTreeNode);
}
so this foreach actually its an iterator so when i use break statement so tis break from the loop but still it holds the object and shell thinks its used by some other program and all so dont use foreach if you using break statement like this :-
Shell32.FolderItems items = folder.Items();
for (int itemIndex = 0; itemIndex < items.Count; itemIndex++)
{
Shell32.FolderItem item = items.Item(itemIndex);
if (item.IsFileSystem && item.IsFolder && !item.IsBrowsable)
{
hasFolders = true;
break;
}
}
and now as above you will never face the error like file/folder is being used by another process so in your application if you are facing then firstly check it out and make sure you are not using any iterator.
Happy to code.
List with ForEach
List Names = new List();
Names.Add("Saurabh");
Names.Add("Somu");
Names.Add("Sandy");
//For every item in the list, say you want to append the last name "Somu" and print it
//WITHOUT ForEach()
foreach (string name in Names)
{
Console.WriteLine(name + " Somu");
}
//WITH ForEach
Names.ForEach(delegate(string name) { Console.WriteLine( name + " Somu" ); });
Names.Add("Saurabh");
Names.Add("Somu");
Names.Add("Sandy");
//For every item in the list, say you want to append the last name "Somu" and print it
//WITHOUT ForEach()
foreach (string name in Names)
{
Console.WriteLine(name + " Somu");
}
//WITH ForEach
Names.ForEach(delegate(string name) { Console.WriteLine( name + " Somu" ); });
Yield Keyword
class Program
{
static void Main(string[] args)
{
List Names = new List();
Names.Add("saurabh");
Names.Add("somu");
Names.Add("vivek");
foreach (string item in GetNames(Names))
{
Console.WriteLine(item);
}
}
public static IEnumerable GetNames(List Names)
{
for (int i = 0; i < Names.Count; i++)
{
yield return Names[i];
}
}
}
{
static void Main(string[] args)
{
List
Names.Add("saurabh");
Names.Add("somu");
Names.Add("vivek");
foreach (string item in GetNames(Names))
{
Console.WriteLine(item);
}
}
public static IEnumerable
{
for (int i = 0; i < Names.Count; i++)
{
yield return Names[i];
}
}
}
?? keyword
?? keyword is used to check null.
Example using if-else statement:-
if (tempString == null)
{
x = "Null string";
}
else
{
x = tempString ;
}
Console.WriteLine(x);
Example using ?? Keyword
string tempString = null;
string x = tempString ?? "Null string";
Console.WriteLine(x); //Prints "Null string"
Example using if-else statement:-
if (tempString == null)
{
x = "Null string";
}
else
{
x = tempString ;
}
Console.WriteLine(x);
Example using ?? Keyword
string tempString = null;
string x = tempString ?? "Null string";
Console.WriteLine(x); //Prints "Null string"
Problem about Instances...
Hii..Frends this is very genuine problem.
Functionality :-When i was developing Window Explorer control for my application then i just stuck in a problem I had three instances of window - explorer.. One is as similar as Window file explorer by which you can drag drop files and that will open in any editor.(We had given additional functionality like to show INF,INI,BAK and ORG files) and other two are as same as Window File - Folder Explorer like in left hand side Folder Explorer(TreeView) and Right hand side ListView which shows all the files with size,Modified date and type of file.and you can sort using coloumn click.(Like Window File detail view in windows) and the third one which is just below of this one has same feature but the root node of this tree will be a path where ever we want to show we said this is destination view and above one is source view .You can drag files from Source listView to Destination TreeView and ListView both and that will copy the whole directory at that path physically and You can add folder from source treeview to destination treeView and we can move folder and files from destination listView to destination treeview.We given the special functionality like we can add new folder,delete the folder and rename the folder.That all the features we have given in all the controls.
Problem:-I have only one control with three instances if i m doing some changes from application and rename and bla bla..n all the tree view has opened a same path then i want to make all the controls as real time like if we add a folder of some path then in all the controls will be the same...So i need some notification then i know the methods about shell if we add , delete and rename from shell then shell will send a notification to application and then WndProc method will send the notification to all the instances and to invoke shell methods i have already make a post related to How to Copy,Delete,Rename from Shell.
If you add delete , add folder,media and other devices and rename and all other changes then how system invokes the message and will reflect real time.
Enjoy the Code..
Functionality :-When i was developing Window Explorer control for my application then i just stuck in a problem I had three instances of window - explorer.. One is as similar as Window file explorer by which you can drag drop files and that will open in any editor.(We had given additional functionality like to show INF,INI,BAK and ORG files) and other two are as same as Window File - Folder Explorer like in left hand side Folder Explorer(TreeView) and Right hand side ListView which shows all the files with size,Modified date and type of file.and you can sort using coloumn click.(Like Window File detail view in windows) and the third one which is just below of this one has same feature but the root node of this tree will be a path where ever we want to show we said this is destination view and above one is source view .You can drag files from Source listView to Destination TreeView and ListView both and that will copy the whole directory at that path physically and You can add folder from source treeview to destination treeView and we can move folder and files from destination listView to destination treeview.We given the special functionality like we can add new folder,delete the folder and rename the folder.That all the features we have given in all the controls.
Problem:-I have only one control with three instances if i m doing some changes from application and rename and bla bla..n all the tree view has opened a same path then i want to make all the controls as real time like if we add a folder of some path then in all the controls will be the same...So i need some notification then i know the methods about shell if we add , delete and rename from shell then shell will send a notification to application and then WndProc method will send the notification to all the instances and to invoke shell methods i have already make a post related to How to Copy,Delete,Rename from Shell.
If you add delete , add folder,media and other devices and rename and all other changes then how system invokes the message and will reflect real time.
Enjoy the Code..
How to Copy,Delete,Rename and Move files and create new directory using Shell32 in C#?
#region Enum
public enum FileOp
{
Move = 0x0001,
Copy = 0x0002,
Delete = 0x0003,
Rename = 0x0004
}
[Flags]
public enum FileOpFlags
{
MultiDestFiles = 0x0001,
ConfirmMouse = 0x0002,
Silent = 0x0004,
RenameCollision = 0x0008,
NoConfirmation = 0x0010,
WantMappingHandle = 0x0020,
AllowUndo = 0x0040,
FilesOnly = 0x0080,
SimpleProgress = 0x0100,
NoConfirmMkDir = 0x0200,
NoErrorUI = 0x0400,
NoCopySecurityAttributes = 0x0800,
NoRecursion = 0x1000,
NoConnectedElements = 0x2000,
WantNukeWarning = 0x4000,
NoRecursiveReparse = 0x8000
}
#endregion
#region Structure
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
public struct SHFILEOPSTRUCT
{
public IntPtr hwnd;
[MarshalAs(UnmanagedType.U4)]
public int wFunc;
public string pFrom;
public string pTo;
public short fFlags;
[MarshalAs(UnmanagedType.Bool)]
public bool fAnyOperationsAborted;
public IntPtr hNameMappings;
public string lpszProgressTitle;
}
#endregion
Import a shell method to copy file from one location to another,delete file,copy file and rename files and folders.
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
Import a shell method to create a new directory.
[DllImport("shell32.dll")]
public static extern int SHCreateDirectoryEx(IntPtr hwnd, string pszPath, IntPtr psa);
To create a new folder :
private const string NULL_STRING = "\0";
newFolderPath is the path where you want to create your directory.
SHCreateDirectoryEx(this.Handle, newFolderPath + NULL_STRING, IntPtr.Zero);
To do all the file operation like move , copy ,delete and rename :-
public bool FileOperation(string sourceFileName, string destinationFileName, FileOp fileOp)
{
bool success = true;
try
{
SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT();
shf.wFunc = (int)fileOp;
shf.fFlags = (short)FileOpFlags.AllowUndo | (short)FileOpFlags.NoConfirmation;
if(!string.IsNullOrEmpty(sourceFileName))
{
shf.pFrom = sourceFileName + NULL_STRING;
}
if(!string.IsNullOrEmpty(destinationFileName))
{
shf.pTo = destinationFileName + NULL_STRING;
}
int result = SHFileOperation(ref shf);
if (result != 0)
{
success = false;
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, Application.ProductName, MessageBoxButtons.OK);
}
return success;
}
How to call this method :-
To Delete the file or folder.
FileOperation(newFolderPath, string.Empty, FileOp.Delete);
To Copy the File or Folder.
FileOperation(sourcePath, destinationPath, FileOp.Move);
To Rename the file or Folder.
FileOperation(sourcePath, destinationPath, FileOp.Rename);
public enum FileOp
{
Move = 0x0001,
Copy = 0x0002,
Delete = 0x0003,
Rename = 0x0004
}
[Flags]
public enum FileOpFlags
{
MultiDestFiles = 0x0001,
ConfirmMouse = 0x0002,
Silent = 0x0004,
RenameCollision = 0x0008,
NoConfirmation = 0x0010,
WantMappingHandle = 0x0020,
AllowUndo = 0x0040,
FilesOnly = 0x0080,
SimpleProgress = 0x0100,
NoConfirmMkDir = 0x0200,
NoErrorUI = 0x0400,
NoCopySecurityAttributes = 0x0800,
NoRecursion = 0x1000,
NoConnectedElements = 0x2000,
WantNukeWarning = 0x4000,
NoRecursiveReparse = 0x8000
}
#endregion
#region Structure
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
public struct SHFILEOPSTRUCT
{
public IntPtr hwnd;
[MarshalAs(UnmanagedType.U4)]
public int wFunc;
public string pFrom;
public string pTo;
public short fFlags;
[MarshalAs(UnmanagedType.Bool)]
public bool fAnyOperationsAborted;
public IntPtr hNameMappings;
public string lpszProgressTitle;
}
#endregion
Import a shell method to copy file from one location to another,delete file,copy file and rename files and folders.
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
Import a shell method to create a new directory.
[DllImport("shell32.dll")]
public static extern int SHCreateDirectoryEx(IntPtr hwnd, string pszPath, IntPtr psa);
To create a new folder :
private const string NULL_STRING = "\0";
newFolderPath is the path where you want to create your directory.
SHCreateDirectoryEx(this.Handle, newFolderPath + NULL_STRING, IntPtr.Zero);
To do all the file operation like move , copy ,delete and rename :-
public bool FileOperation(string sourceFileName, string destinationFileName, FileOp fileOp)
{
bool success = true;
try
{
SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT();
shf.wFunc = (int)fileOp;
shf.fFlags = (short)FileOpFlags.AllowUndo | (short)FileOpFlags.NoConfirmation;
if(!string.IsNullOrEmpty(sourceFileName))
{
shf.pFrom = sourceFileName + NULL_STRING;
}
if(!string.IsNullOrEmpty(destinationFileName))
{
shf.pTo = destinationFileName + NULL_STRING;
}
int result = SHFileOperation(ref shf);
if (result != 0)
{
success = false;
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, Application.ProductName, MessageBoxButtons.OK);
}
return success;
}
How to call this method :-
To Delete the file or folder.
FileOperation(newFolderPath, string.Empty, FileOp.Delete);
To Copy the File or Folder.
FileOperation(sourcePath, destinationPath, FileOp.Move);
To Rename the file or Folder.
FileOperation(sourcePath, destinationPath, FileOp.Rename);
How to create FilePropertyDialog like Windows in C#?
#region Enum
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHELLEXECUTEINFO
{
public int cbSize;
public uint fMask;
public IntPtr hwnd;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpVerb;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpFile;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpParameters;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpDirectory;
public int nShow;
public IntPtr hInstApp;
public IntPtr lpIDList;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpClass;
public IntPtr hkeyClass;
public uint dwHotKey;
public IntPtr hIcon;
public IntPtr hProcess;
}
#endregion
private const int SW_SHOW = 5;
private const uint SEE_MASK_INVOKEIDLIST = 12;
[DllImport("shell32.dll")]
static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);
Pass the file name for which you want to see the file property dialog.
public static void ShowFileProperties(string Filename)
{
SHELLEXECUTEINFO shellInfo = new SHELLEXECUTEINFO();
shellInfo .cbSize = System.Runtime.InteropServices.Marshal.SizeOf(info);
shellInfo .lpVerb = "properties";
shellInfo .lpFile = Filename;
shellInfo .nShow = SW_SHOW;
shellInfo .fMask = SEE_MASK_INVOKEIDLIST;
ShellExecuteEx(ref info);
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHELLEXECUTEINFO
{
public int cbSize;
public uint fMask;
public IntPtr hwnd;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpVerb;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpFile;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpParameters;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpDirectory;
public int nShow;
public IntPtr hInstApp;
public IntPtr lpIDList;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpClass;
public IntPtr hkeyClass;
public uint dwHotKey;
public IntPtr hIcon;
public IntPtr hProcess;
}
#endregion
private const int SW_SHOW = 5;
private const uint SEE_MASK_INVOKEIDLIST = 12;
[DllImport("shell32.dll")]
static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);
Pass the file name for which you want to see the file property dialog.
public static void ShowFileProperties(string Filename)
{
SHELLEXECUTEINFO shellInfo = new SHELLEXECUTEINFO();
shellInfo .cbSize = System.Runtime.InteropServices.Marshal.SizeOf(info);
shellInfo .lpVerb = "properties";
shellInfo .lpFile = Filename;
shellInfo .nShow = SW_SHOW;
shellInfo .fMask = SEE_MASK_INVOKEIDLIST;
ShellExecuteEx(ref info);
}
How many instances are running in my application using C# ?
#region Directives
using System.text;
using System.Threading;
using System.Reflection;
#endregion
public class TestApplication
{
#region Private Fields
The default instance
private static TestApplication DefValue = new TestApplication ();
The system-wide semaphore
private Semaphore semaphore;
Initial count for the semaphore(Randonm you can choose any big count)
private const int MAXCOUNT = 10000;
private static bool _pvInstance ;
#endregion
#region Properties
The PrevInstance property returns True if there was a previous instance running when the default instance was created
public static bool PrevInstance
{
get
{
return _pvInstance ;
}
}
Return the total number of instances of the same application that are currently running
public static int InstanceCount
{
get
{
// release the semaphore and grab the previous count
int prevCount = DefValue.semaphore.Release();
// acquire the semaphore again
DefValue.semaphore.WaitOne();
// evaluate number of other instances that are currently running.
return MAXCOUNT - prevCount;
}
}
#endregion
Constructor.
private TestApplication ()
{
// create a named (system-wide semaphore)
bool ownership = false;
// create the semaphore or get a reference to an existing semaphore
string appName = "TestApplication _" + Assembly.GetExecutingAssembly().Location.Replace(":", string.Empty).Replace("\\", string.Empty);
semaphore = new Semaphore( MAXCOUNT, MAXCOUNT, appName , out ownership);
// decrement its value
semaphore.WaitOne();
// if we got ownership, this app has no previous instances
_prevInstance = !ownership;
}
Destructor to destroy.
~TestApplication ()
{
// increment the semaphore when the application terminates
semaphore.Release();
}
}
using System.text;
using System.Threading;
using System.Reflection;
#endregion
public class TestApplication
{
#region Private Fields
The default instance
private static TestApplication DefValue = new TestApplication ();
The system-wide semaphore
private Semaphore semaphore;
Initial count for the semaphore(Randonm you can choose any big count)
private const int MAXCOUNT = 10000;
private static bool _pvInstance ;
#endregion
#region Properties
The PrevInstance property returns True if there was a previous instance running when the default instance was created
public static bool PrevInstance
{
get
{
return _pvInstance ;
}
}
Return the total number of instances of the same application that are currently running
public static int InstanceCount
{
get
{
// release the semaphore and grab the previous count
int prevCount = DefValue.semaphore.Release();
// acquire the semaphore again
DefValue.semaphore.WaitOne();
// evaluate number of other instances that are currently running.
return MAXCOUNT - prevCount;
}
}
#endregion
Constructor.
private TestApplication ()
{
// create a named (system-wide semaphore)
bool ownership = false;
// create the semaphore or get a reference to an existing semaphore
string appName = "TestApplication _" + Assembly.GetExecutingAssembly().Location.Replace(":", string.Empty).Replace("\\", string.Empty);
semaphore = new Semaphore( MAXCOUNT, MAXCOUNT, appName , out ownership);
// decrement its value
semaphore.WaitOne();
// if we got ownership, this app has no previous instances
_prevInstance = !ownership;
}
Destructor to destroy.
~TestApplication ()
{
// increment the semaphore when the application terminates
semaphore.Release();
}
}
How to Create a Zip file using C#
public bool CreateZip(string ZipFileName)
{
try
{
Create an empty zip file
byte[] ZipFolder = new byte[]{100,75,50,16,10,5,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
FileStream fs = File.Create(ZipFileName);
fs.Write(ZipFolder , 0, ZipFolder.Length);
fs.Flush();
fs.Close();
fs = null;
}
catch(Exception ignore)
{
}
return true;
}
{
try
{
Create an empty zip file
byte[] ZipFolder = new byte[]{100,75,50,16,10,5,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
FileStream fs = File.Create(ZipFileName);
fs.Write(ZipFolder , 0, ZipFolder.Length);
fs.Flush();
fs.Close();
fs = null;
}
catch(Exception ignore)
{
}
return true;
}
How to open a zip file using C# ?
#region Namespace
using Shell32;
#endregion
namespace TestApplicationToZip
{
class ZipApplication
{
public static void Main(string[] args)
{
Create the object of shell.
Shell sh = new Shell();
Create a namespace and folderItem for the existing folder path.
Folder ShellFolder = sh.NameSpace("D:\\saurabh.zip");
Folder DirectoryFolder = sh.NameSpace("D:\\Unzipped Files");
Traverse each file.
foreach (FolderItem folderItem in ShellFolder .Items())
{
DirectoryFolder .CopyHere(folderItem ,o);
}
}
}
}
Enjoy the code.
using Shell32;
#endregion
namespace TestApplicationToZip
{
class ZipApplication
{
public static void Main(string[] args)
{
Create the object of shell.
Shell sh = new Shell();
Create a namespace and folderItem for the existing folder path.
Folder ShellFolder = sh.NameSpace("D:\\saurabh.zip");
Folder DirectoryFolder = sh.NameSpace("D:\\Unzipped Files");
Traverse each file.
foreach (FolderItem folderItem in ShellFolder .Items())
{
DirectoryFolder .CopyHere(folderItem ,o);
}
}
}
}
Enjoy the code.
Differences between Connected and disconnected architecture ?
Hii friends,Today one of my frend ask about what approach is better connected or disconnected architecture ..So let me explain more about this problem :-
As the nature of HTTP protocol,.Net web applications are always disconnected so your problem is about connected or disconnected data models.
"connected" data is always faster as compare to "disconnected" because of the internal optimizations provided by the data provider,data adopters and others like data tables but always remeber that fetch out the data when you need so disconnected data model is good.
Connected :-
**User can get the data from database in connection state using data reader,adaptor,data table.1 :- Using this communication will possible in between the front end & backend (UI and database).
2 :- This command object have some parameters and have some methods to execute stored procedure ExecuteNonQuery(),ExecuteReader(),ExecuteScalar(),
ExecuteXMLReader()
ExecuteNonQuery :- For executing DML statements.
ExecuteReader :- This method returns DataReader.
ExecuteScalar :- This method is used for executing those SQL statements which generates single value.
ExecuteXMLReader :- This method is mainly used for reading an XML file content.
Disconnected :-
** User can get the data from database in connectionless state using data set.
As the nature of HTTP protocol,.Net web applications are always disconnected so your problem is about connected or disconnected data models.
"connected" data is always faster as compare to "disconnected" because of the internal optimizations provided by the data provider,data adopters and others like data tables but always remeber that fetch out the data when you need so disconnected data model is good.
Connected :-
**User can get the data from database in connection state using data reader,adaptor,data table.1 :- Using this communication will possible in between the front end & backend (UI and database).
2 :- This command object have some parameters and have some methods to execute stored procedure ExecuteNonQuery(),ExecuteReader(),ExecuteScalar(),
ExecuteXMLReader()
ExecuteNonQuery :- For executing DML statements.
ExecuteReader :- This method returns DataReader.
ExecuteScalar :- This method is used for executing those SQL statements which generates single value.
ExecuteXMLReader :- This method is mainly used for reading an XML file content.
Disconnected :-
** User can get the data from database in connectionless state using data set.
What do you meant by Containment in C#?
Containment is the replacement of inheritence,no no if inheritance isn’t the right choice,then the answer is containment, also known as aggregation. Rather than saying that an object is an example of another object, an instance of that other object will be contained inside the object. So,instead of having a class look like a string, the class will contain a string (or array, or hash table).
The default design choice should be containment, and you should switch to inheritance only if needed(i.e., if there really is an “is-a” relationship).
The default design choice should be containment, and you should switch to inheritance only if needed(i.e., if there really is an “is-a” relationship).
How to handle generic errors in WinApp using C# ?
Pass your exception or error through catch block to this method this will catch your error and show the messagebox regarding that error.
Method which take error exception as a parameter and handle that error.
public static void LogError(Exception ex)
{
string sourceName = "Application Name";
int errorCode = "99";
string message = "The application encountered an unknown error:";
msg += "\r\nExecuting Method: " + new System.Diagnostics.StackFrame(1, false).GetMethod().Name;
message += "\r\nError Message: " + ex.Message;
EventLog.WriteEntry(sourceName , msg, EventLogEntryType.Error, errorCode );
MessageBox.Show(msg, "ERROR", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
}
Method which take error exception as a parameter and handle that error.
public static void LogError(Exception ex)
{
string sourceName = "Application Name";
int errorCode = "99";
string message = "The application encountered an unknown error:";
msg += "\r\nExecuting Method: " + new System.Diagnostics.StackFrame(1, false).GetMethod().Name;
message += "\r\nError Message: " + ex.Message;
EventLog.WriteEntry(sourceName , msg, EventLogEntryType.Error, errorCode );
MessageBox.Show(msg, "ERROR", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
}
What is interface and why we implement interfaces ?
Interface defined by using interface keyword .In visualstudio you can directly add class as a interface its not a class it behaves as a template of the class. Interfaces describe a group of related functionalities that can belong to any class or struct.Interfaces are provided in C# as a replacement of multiple inheritance because C# does not support multiple inheritance and it's very necessary to inherit the behaviour of one or more classes.classes can only implement the methods defined in the interface because in C#, an interface is a built-in keyword that declares a reference type that includes method declarations. if a base class implements an interface, the derived class inherits that implementation.
I am giving an example to better understand :-
Interface which contains profile name strings
public interface IProfile
{
string FirstName {get;}
string LastName {get;}
}
Implements IloggedUser interface.
public interface ILoggedUser
{
IProfile Profile
{
get;
set;
}
}
Class LoggedUser which implements ILoggedUser interface.
public class LoggedUser : ILoggedUser
{
protected IProfile _profile = null;
Constructor
public LoggedUser(IProfile Profile)
{
_profile=Profile;
}
public static LoggedUser Create(IProfile Profile)
{
LoggedUser User = new LoggedUser(Profile);
return User;
}
public IProfile Profile
{
get
{
if (_profile== null)
{
return _profile;
}
}
set
{
_profile=value;
}
}
}
Class profile which implements IProfile interface.
public class Profile : IProfile
{
string _firstName = string.Empty;
string _lastName = string.Empty;
public string FirstName
{
get
{
return _firstName;
}
}
public string LastName
{
get
{
return _lastName;
}
}
}
I am giving an example to better understand :-
Interface which contains profile name strings
public interface IProfile
{
string FirstName {get;}
string LastName {get;}
}
Implements IloggedUser interface.
public interface ILoggedUser
{
IProfile Profile
{
get;
set;
}
}
Class LoggedUser which implements ILoggedUser interface.
public class LoggedUser : ILoggedUser
{
protected IProfile _profile = null;
Constructor
public LoggedUser(IProfile Profile)
{
_profile=Profile;
}
public static LoggedUser Create(IProfile Profile)
{
LoggedUser User = new LoggedUser(Profile);
return User;
}
public IProfile Profile
{
get
{
if (_profile== null)
{
return _profile;
}
}
set
{
_profile=value;
}
}
}
Class profile which implements IProfile interface.
public class Profile : IProfile
{
string _firstName = string.Empty;
string _lastName = string.Empty;
public string FirstName
{
get
{
return _firstName;
}
}
public string LastName
{
get
{
return _lastName;
}
}
}
How to combine two images into one image in C#?
using System.Drawing;
public static System.Drawing.Bitmap Combine(string[] files)
{
Create a list for images and read images
List images = new List();
Bitmap finalImage = null;
try
{
int width = 0;
int height = 0;
foreach (string image in files)
{
create a Bitmap from the file and add it to the list. Bitmap bitmap = new Bitmap(image);
Update the size of the final bitmap.
width += bitmap.Width;
if(bitmap.Height > height )
{
height = bitmap.Height ;
}
else
{
height = height ;
}
images.Add(bitmap);
}
create a bitmap to hold the combined image.
finalImage = new Bitmap(width, height);
Get a graphics object from the image so we can draw on it.
using (Graphics g = Graphics.FromImage(finalImage))
{
set background color.
g.Clear(Color.Black);
Go through each image and draw it on the final image.
int offset = 0;
foreach (Bitmap image in images)
{
g.DrawImage(image,
new System.Drawing.Rectangle(offset, 0, image.Width, image.Height));
offset += image.Width;
}
}
return finalImage;
}
catch(Exception ex)
{
if (finalImage != null)
{
finalImage.Dispose();
}
throw ex;
}
finally
{
//clean up memory
foreach (Bitmap image in images)
{
image.Dispose();
}
}
}
public static System.Drawing.Bitmap Combine(string[] files)
{
Create a list for images and read images
List
Bitmap finalImage = null;
try
{
int width = 0;
int height = 0;
foreach (string image in files)
{
create a Bitmap from the file and add it to the list. Bitmap bitmap = new Bitmap(image);
Update the size of the final bitmap.
width += bitmap.Width;
if(bitmap.Height > height )
{
height = bitmap.Height ;
}
else
{
height = height ;
}
images.Add(bitmap);
}
create a bitmap to hold the combined image.
finalImage = new Bitmap(width, height);
Get a graphics object from the image so we can draw on it.
using (Graphics g = Graphics.FromImage(finalImage))
{
set background color.
g.Clear(Color.Black);
Go through each image and draw it on the final image.
int offset = 0;
foreach (Bitmap image in images)
{
g.DrawImage(image,
new System.Drawing.Rectangle(offset, 0, image.Width, image.Height));
offset += image.Width;
}
}
return finalImage;
}
catch(Exception ex)
{
if (finalImage != null)
{
finalImage.Dispose();
}
throw ex;
}
finally
{
//clean up memory
foreach (Bitmap image in images)
{
image.Dispose();
}
}
}
Location of opening of dialog boxes(window form) in C#
In my application i used some dialog boxes like about of company some customize message boxes and all that in some dialog boxes I used start position as Center parent but i forget to pass the IWin32Window Owner in show dialog as a parameter regarding that when focus is lost from my application then dialog took desktop as a parent and opens in different locations so always pass window owner as a parameter.
About aboutInfo = new About();
aboutInfo .ShowDialog(this);
or,
aboutInfo .ShowDialog(this.toplevelcontrol);
About aboutInfo = new About();
aboutInfo .ShowDialog(this);
or,
aboutInfo .ShowDialog(this.toplevelcontrol);
How to set image resolution and paint it in C# ?
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Imaging;
public class Form1 : System.Windows.Forms.Form
{
Constructor.
public Form1()
{
InitializeComponent();
}
Initialize all the controls.
private void InitializeComponent()
{
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Text = "";
this.Resize += new System.EventHandler(this.Form1_Resize);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
}
Main method(Entry point).
public static void Main()
{
Application.Run(new Form1());
}
Handles the paint event.Create the grapics for the image,then set the resolution and then draw the image.
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
Bitmap bmp = new Bitmap("winter.jpg");
g.FillRectangle(Brushes.White, this.ClientRectangle);
bmp.SetResolution(600f, 600f);
g.DrawImage(bmp, 0, 0);
bmp.SetResolution(1200f, 1200f);
g.DrawImage(bmp, 180, 0);
}
Handles the resize event.
private void Form1_Resize(object sender, System.EventArgs e)
{
Invalidate();
}
}
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Imaging;
public class Form1 : System.Windows.Forms.Form
{
Constructor.
public Form1()
{
InitializeComponent();
}
Initialize all the controls.
private void InitializeComponent()
{
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Text = "";
this.Resize += new System.EventHandler(this.Form1_Resize);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
}
Main method(Entry point).
public static void Main()
{
Application.Run(new Form1());
}
Handles the paint event.Create the grapics for the image,then set the resolution and then draw the image.
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
Bitmap bmp = new Bitmap("winter.jpg");
g.FillRectangle(Brushes.White, this.ClientRectangle);
bmp.SetResolution(600f, 600f);
g.DrawImage(bmp, 0, 0);
bmp.SetResolution(1200f, 1200f);
g.DrawImage(bmp, 180, 0);
}
Handles the resize event.
private void Form1_Resize(object sender, System.EventArgs e)
{
Invalidate();
}
}
C# Tutorial (Chapter - 1) Introduction about C# and .Net framework(1 :- .Net Plateform)
I :-.Net Plateform :-
The Microsoft® .NET platform provides all of the tools and technologies that
you need to build distributed Web applications. It exposes a languageindependent,
consistent programming model across all tiers of an application
while providing seamless interoperability with, and easy migration from,
existing technologies. The .NET platform fully supports the Internet’s platformneutral, standards-based technologies, including HTTP, Extensible Markup
Language (XML), and Simple Object Access Protocol (SOAP).
II :-The .NET Building Block Services :-
The .Net building block services are distributed programmable services that are availaible in both offline and online.A service can be invoked on stand alone computer not connected to the internet,provided by the server which is running inside from the company oer accessed by internet, This service can be used from the plateform which supports SOAP.Services include identity, notification and messaging,
personalization, schematized storage, calendar, directory, search, and software
delivery.
III :-The .NET Enterprise Servers :-
1: Microft Sql server - 2000
2: Microsoft Biztalk sever - 2000
3: Microsoft Host integration server - 2000
4: Microsoft Exchange 2000 Enterprise server
5: Microst Application center - 2000
6: Microsoft Internet security server - 2000
Microsoft Sql server - 2000 :- Supports XML functionality, support for Worldwide Web Consortium (W3C) standards, manipulate XML data by using Transact SQL (T-SQL), flexible Web-based analysis, and secure access to your data over the Web by using HTTP.
Microsoft Internet security server - 2000 :- Provides secure, fast, and manageable Internet connectivity. Internet Security and multilayer enterprise firewall and a scalable high-performance Web cache. It builds on Windows 2000 security.
Microst Application center - 2000 :- Provides a deployment and management tool for high-availability Web applications.
Microsoft Exchange 2000 Enterprise server :- Builds on the powerful Exchange messaging and collaboration technology by ntroducing new features, and further increasing the reliability,scalability, and performance of its core architecture.
Microsoft Biztalk sever - 2000 :- Provides enterprise application integration (EAI), business-to-business integration and to build dynamic business processes,the span applications and plate forms.
Microsoft Host integration server - 2000 Provides the best way to embrace Internet, intranet, and client/server technologies.
IV :-The .NET Framework Components :-
1:-Common Language Runtime
2:- Base Class Library
3:- ADO.NET: Data and XML
4:- Web Forms and Services
5:- User Interface
CLR(Comman Language Runtime) :- Central to the .NET framework is its run-time execution environment, known as the Common Language Runtime (CLR) or the .NET runtime. Code running under the control of the CLR is often termed
managed code.However, before it can be executed by the CLR, any sourcecode that we develop (in C# or some other language) needs to be compiled. Compilation occurs in two steps in .NET:
1. Compilation of source code to Microsoft Intermediate Language (MS-IL)
2. Compilation of IL to platform-specific code by the CLR
Components of CLR :-
1 :-Class loader : Manages metadata, as well as the loading and layout of classes.
ClassLoader classLoader = TestClass.getClassLoader();
URL url = cl.getResource("someFileName");
2 :-Garbage collector (GC) :-The garbage collector is .NET's answer to memory management,Having the application code responsible for de-allocating memory is the technique used by lower-level,high-performance languages such as C++. It is efficient, and it has the advantage that (in general)resources are never occupied for longer than unnecessary. The big disadvantage, however, is the frequency of bugs. Code that requests memory also should explicitly inform the system when it no longer requires that memory. However, it is easy to overlook this, resulting in memory leaks.Provides automatic lifetime management of all of your objects. This is a multiprocessor, scalable garbage collector.
3 :-Security engine :-It based on the origin of the code.
4 :-Debug engine :- Debug your program and trace the execution of code.
5:-Code manager :-Manages the code execution.
6 :-Exception manager :- It provides structured exception management,which is integrated with Windows Structured Exception Handling (SEH),provides all the system exception classes.
7 :-Thread support :-Supports multi threaded programming.
8 :-COM :-Provides Interoperability class and marshalling to and from COM.
9 :-Type checker :-This will not allow unsafe typecasting and uninitialized variables Il verifies guaranteed type safety.
10 :-Microsoft intermediate language :-Converts MSIL to native code.
11 :- Base Class Library :- Executes run time.
2:-Base Class library :- This library contains namespaces like header files in C,C++,It expose features at run time and provide some high services.
I am mentioning namespace and about their services :-
System.Collections :- You can see all the interfaces and classes included in this namespace from below link :-
http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx
The Microsoft® .NET platform provides all of the tools and technologies that
you need to build distributed Web applications. It exposes a languageindependent,
consistent programming model across all tiers of an application
while providing seamless interoperability with, and easy migration from,
existing technologies. The .NET platform fully supports the Internet’s platformneutral, standards-based technologies, including HTTP, Extensible Markup
Language (XML), and Simple Object Access Protocol (SOAP).
II :-The .NET Building Block Services :-
The .Net building block services are distributed programmable services that are availaible in both offline and online.A service can be invoked on stand alone computer not connected to the internet,provided by the server which is running inside from the company oer accessed by internet, This service can be used from the plateform which supports SOAP.Services include identity, notification and messaging,
personalization, schematized storage, calendar, directory, search, and software
delivery.
III :-The .NET Enterprise Servers :-
1: Microft Sql server - 2000
2: Microsoft Biztalk sever - 2000
3: Microsoft Host integration server - 2000
4: Microsoft Exchange 2000 Enterprise server
5: Microst Application center - 2000
6: Microsoft Internet security server - 2000
Microsoft Sql server - 2000 :- Supports XML functionality, support for Worldwide Web Consortium (W3C) standards, manipulate XML data by using Transact SQL (T-SQL), flexible Web-based analysis, and secure access to your data over the Web by using HTTP.
Microsoft Internet security server - 2000 :- Provides secure, fast, and manageable Internet connectivity. Internet Security and multilayer enterprise firewall and a scalable high-performance Web cache. It builds on Windows 2000 security.
Microst Application center - 2000 :- Provides a deployment and management tool for high-availability Web applications.
Microsoft Exchange 2000 Enterprise server :- Builds on the powerful Exchange messaging and collaboration technology by ntroducing new features, and further increasing the reliability,scalability, and performance of its core architecture.
Microsoft Biztalk sever - 2000 :- Provides enterprise application integration (EAI), business-to-business integration and to build dynamic business processes,the span applications and plate forms.
Microsoft Host integration server - 2000 Provides the best way to embrace Internet, intranet, and client/server technologies.
IV :-The .NET Framework Components :-
1:-Common Language Runtime
2:- Base Class Library
3:- ADO.NET: Data and XML
4:- Web Forms and Services
5:- User Interface
CLR(Comman Language Runtime) :- Central to the .NET framework is its run-time execution environment, known as the Common Language Runtime (CLR) or the .NET runtime. Code running under the control of the CLR is often termed
managed code.However, before it can be executed by the CLR, any sourcecode that we develop (in C# or some other language) needs to be compiled. Compilation occurs in two steps in .NET:
1. Compilation of source code to Microsoft Intermediate Language (MS-IL)
2. Compilation of IL to platform-specific code by the CLR
Components of CLR :-
1 :-Class loader : Manages metadata, as well as the loading and layout of classes.
ClassLoader classLoader = TestClass.getClassLoader();
URL url = cl.getResource("someFileName");
2 :-Garbage collector (GC) :-The garbage collector is .NET's answer to memory management,Having the application code responsible for de-allocating memory is the technique used by lower-level,high-performance languages such as C++. It is efficient, and it has the advantage that (in general)resources are never occupied for longer than unnecessary. The big disadvantage, however, is the frequency of bugs. Code that requests memory also should explicitly inform the system when it no longer requires that memory. However, it is easy to overlook this, resulting in memory leaks.Provides automatic lifetime management of all of your objects. This is a multiprocessor, scalable garbage collector.
3 :-Security engine :-It based on the origin of the code.
4 :-Debug engine :- Debug your program and trace the execution of code.
5:-Code manager :-Manages the code execution.
6 :-Exception manager :- It provides structured exception management,which is integrated with Windows Structured Exception Handling (SEH),provides all the system exception classes.
7 :-Thread support :-Supports multi threaded programming.
8 :-COM :-Provides Interoperability class and marshalling to and from COM.
9 :-Type checker :-This will not allow unsafe typecasting and uninitialized variables Il verifies guaranteed type safety.
10 :-Microsoft intermediate language :-Converts MSIL to native code.
11 :- Base Class Library :- Executes run time.
2:-Base Class library :- This library contains namespaces like header files in C,C++,It expose features at run time and provide some high services.
I am mentioning namespace and about their services :-
System.Collections :- You can see all the interfaces and classes included in this namespace from below link :-
http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx
C# Tutorials
Hello to all, My next thread is about C#,In my next thread i will divide the C# thread into chapters each chapter will contain all the details about C# and .Net framework its a step by step process so go through to all the thread and please post a comment or email me at saurabhjnumca@gmail.com about this thread please give critics about this thread.If you will study the coming thread then you will able to explain about .net and you can easily code in C# .
Regards,
Saurabh Singh
Regards,
Saurabh Singh
How to create a session manager in .Net ?
To create a SessionManager to save User objects in memory. It would be HashMap of HaspMaps.
It can be used as:
SessionManager MySessionManager= New SessionManager()
Student S1 = New Student ("Saurabh");
Student S2 = New Student ("Sandeep");
Student S3 = New Student ("Deepak");
//To create session
MySessionManager.createSession(S1);
MySessionManager.createSession(S2);
//SAVING S1 MARKS
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S1, "Physics", phyisicsMarks); //Physics is the key
Marks chemMarks New Marks("Chemistry",85);
MySessionManager.Save(S1, "Chemistry",chemistryMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S1, "Mathematics" ,mathsMarks);
//SAVING S2 MARKS
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S2, "Physics", phyMarks); //Physics is the key
Marks chemMarks New Marks("Chemistry",85)
MySessionManager.Save(S2, "Chemistry",chemMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S2, "Mathematics" ,mathsMarks);
//SAVING S3 MARKS. NOTE: SESSION OF S3 IS NOT AVAILABLE. SO FIRST SESSION OF
S3 SHOULD BE CREATED AND THEN DATA SHOULD BE SAVED
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S3, "Physics", phyMarks); //”Physics” is the key
Marks chemMarks New Marks("Chemistry",85);
MySessionManager.Save(S3, "Chemistry",chemMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S3, "Mathematics" ,mathsMarks);
///How to retrieve data
Out.Print ("Phyiscis Marks of S1," & MySessionManager.get(S1, "Physics").marks);
Out.Print ("Phyiscis Marks of S3," & MySessionManager.get(S1, "chemistry").marks);
IN REAL WORLD SCENARIO, S1, S2, S3 SHOULD NOT BE PASSED TO
MYSESSIONMANAGER. THEY WOULD BE OBTAINED FROM CONTEXT.
It can be used as:
SessionManager MySessionManager= New SessionManager()
Student S1 = New Student ("Saurabh");
Student S2 = New Student ("Sandeep");
Student S3 = New Student ("Deepak");
//To create session
MySessionManager.createSession(S1);
MySessionManager.createSession(S2);
//SAVING S1 MARKS
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S1, "Physics", phyisicsMarks); //Physics is the key
Marks chemMarks New Marks("Chemistry",85);
MySessionManager.Save(S1, "Chemistry",chemistryMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S1, "Mathematics" ,mathsMarks);
//SAVING S2 MARKS
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S2, "Physics", phyMarks); //Physics is the key
Marks chemMarks New Marks("Chemistry",85)
MySessionManager.Save(S2, "Chemistry",chemMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S2, "Mathematics" ,mathsMarks);
//SAVING S3 MARKS. NOTE: SESSION OF S3 IS NOT AVAILABLE. SO FIRST SESSION OF
S3 SHOULD BE CREATED AND THEN DATA SHOULD BE SAVED
Marks phyMarks = New Marks ("Physcis", 90);
MySessionManager.Save(S3, "Physics", phyMarks); //”Physics” is the key
Marks chemMarks New Marks("Chemistry",85);
MySessionManager.Save(S3, "Chemistry",chemMarks);
Marks mathsmarks = New Marks("Mathematics",100);
MySessionManager.Save(S3, "Mathematics" ,mathsMarks);
///How to retrieve data
Out.Print ("Phyiscis Marks of S1," & MySessionManager.get(S1, "Physics").marks);
Out.Print ("Phyiscis Marks of S3," & MySessionManager.get(S1, "chemistry").marks);
IN REAL WORLD SCENARIO, S1, S2, S3 SHOULD NOT BE PASSED TO
MYSESSIONMANAGER. THEY WOULD BE OBTAINED FROM CONTEXT.
Tech-Giant(Jargons.. for Professionals): How to take Screenshot of panel,control and save it in a JPG format ?
How to take Screenshot of panel,control and save it in a JPG format ?
You can create a bitmap of screen and then save it give the stream or fileName and then dispose the object of screenshot.
Bitmap theScreenShot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
theScreenShot.Save(stream_or_filename, ImageFormat.Jpeg);
theScreenShot.Dispose();
Another way to save the panel as a jpg format and you can take a print of your control using below method.
Use this event on your form :-
_document.PrintPage += new PrintPageEventHandler(document_PrintPage);
/// Prepare the page to be print for the area of the control to be printed.
private void document_PrintPage(object sender, PrintPageEventArgs e)
{
this.Dock = System.Windows.Forms.DockStyle.None;
this.Size = Temp_Image.Size;
//Takes away focus from any printed controls to make sure output is what we want.
this.Focus();
this.Refresh();
this.DrawToBitmap(Temp_Image, New System.Drawing.Rectangle(0, 0, Temp_Image.Width, Temp_Image.Height));
this.Dock = System.Windows.Forms.DockStyle.Fill;
e.Graphics.DrawImage(Temp_Image, e.MarginBounds);
e.Graphics.Clip = new Region(e.MarginBounds);
}
By this method you can print your control you just pass the object of your control (control will be panel,treeView,listView)and this will calculate the height ,width and then call the print method ,print preview or save as jpg file.
Bitmap theScreenShot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
theScreenShot.Save(stream_or_filename, ImageFormat.Jpeg);
theScreenShot.Dispose();
Another way to save the panel as a jpg format and you can take a print of your control using below method.
Use this event on your form :-
_document.PrintPage += new PrintPageEventHandler(document_PrintPage);
/// Prepare the page to be print for the area of the control to be printed.
private void document_PrintPage(object sender, PrintPageEventArgs e)
{
this.Dock = System.Windows.Forms.DockStyle.None;
this.Size = Temp_Image.Size;
//Takes away focus from any printed controls to make sure output is what we want.
this.Focus();
this.Refresh();
this.DrawToBitmap(Temp_Image, New System.Drawing.Rectangle(0, 0, Temp_Image.Width, Temp_Image.Height));
this.Dock = System.Windows.Forms.DockStyle.Fill;
e.Graphics.DrawImage(Temp_Image, e.MarginBounds);
e.Graphics.Clip = new Region(e.MarginBounds);
}
By this method you can print your control you just pass the object of your control (control will be panel,treeView,listView)and this will calculate the height ,width and then call the print method ,print preview or save as jpg file.
Order of Event firing in ASP.Net
Event firing order becomes critically important when you add event handling code to master pages and the content forms based on them. The following events occur when ASP.NET renders a page. I’ve listed these events in the order in which they occur.
1 :-Content Page Pre Initializes
2 :-Master Page Child Controls Initialize
3 :-Content Page Child Controls Initialize
4 :-Master Page Initializes
5 :-Content Page Initializes
6 :-Content Page Initialize Complete
7 :-Content Page Pre Loads
8 :-Content Page Loads
9 :-Master Page Loads
10 :-Master Page Child Controls Load
11 :-Content Page Child Controls Load
12 :-Content Page Load Complete
1 :-Content Page Pre Initializes
2 :-Master Page Child Controls Initialize
3 :-Content Page Child Controls Initialize
4 :-Master Page Initializes
5 :-Content Page Initializes
6 :-Content Page Initialize Complete
7 :-Content Page Pre Loads
8 :-Content Page Loads
9 :-Master Page Loads
10 :-Master Page Child Controls Load
11 :-Content Page Child Controls Load
12 :-Content Page Load Complete
Lambda Expressions in C#
Lambda expressions makes the searching life much easier.Have a look on this example :-
public class TestLambdaProgram
{
public static void Main( string[] args )
{
List names = new List();
names.Add(“Saurabh”);
names.Add("Garima");
names.Add(“Vivek”);
names.Add(“Sandeep”);
string stringResult = names.Find( name => name.Equals(“Garima”));
}
You can print the whole list using this method :-
new List(names ).foreach(name => Console.WriteLine(name));
public class TestLambdaProgram
{
public static void Main( string[] args )
{
List
names.Add(“Saurabh”);
names.Add("Garima");
names.Add(“Vivek”);
names.Add(“Sandeep”);
string stringResult = names.Find( name => name.Equals(“Garima”));
}
You can print the whole list using this method :-
new List
Basics of .Net (What is IL,CLR,CTS,CLS ?)
1: IL(Intermediate Language) :-(IL)Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code is compiled to IL. This IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler. Microsoft Intermediate Language (MSIL) is a language used as the output of a number of compilers (C#, VB, .NET, and so forth). The ILDasm (Intermediate Language Disassembler) program that ships with the .NET Framework SDK (FrameworkSDK\Bin\ildasm.exe) allows the user to see MSIL code in human-readable format. By using this utility, we can open any .NET executable file (EXE or DLL) and see MSIL code.
MSIL commands are as follows:
ldstr string :—loads the string constant onto the stack.
call function(parameters) :—calls the static function. Parameters for the function should be loaded onto the stack before this call.
pop :—pops a value from the stack. Used when we don't need to store a value in the variable.
ret :—returns from a function.
I will discuss about MSIL in my next article.
2 :- CLR(Comman Language Runtime) Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework.It is the implementation of CLI .The core runtime engine in the microsoft .net framework for executing assemblies. All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program. For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL, Java has Java Virtual Machine etc. Similarly .NET has CLR. Internet Exlorer is the example of hosting CLR. CLR have following qualities :-
Garbage Collection :- CLR automatically manages memory thus eliminating memory leaks. When objects are not referred GC automatically releases those memories thus providing efficient memory management.
Code Access Security :- CAS grants rights to program depending on the security configuration of the machine. Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file. CAS will take care that the code runs under the environment of machines security configuration.
Code Verification :- This ensures proper code execution and type safety while the code runs. It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.
IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL
code.
3 :- CTS(Comman Type System) :- In order that two language communicate smoothly CLR has CTS (Common Type System).Example
in VB you have “Integer” and in C++ you have “long” in c u have "int" these datatypes are not compatible so the interfacing between them is very complicated. In order to able that two different languages can 1. Basic .NET Framework communicate Microsoft introduced Common Type System. So “Integer” datatype in VB6 and
“int” datatype in C++ will convert it to System.int32 which is datatype of CTS. CLS which is covered in the coming question is subset of CTS.
4 :-CLS(Common Language Specification) :- This is a subset of the CTS which all .NET languages are expected to support. It was always a
dream of Microsoft to unite all different languages in to one umbrella and CLS is one step towards that. Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.
MSIL commands are as follows:
ldstr string :—loads the string constant onto the stack.
call function(parameters) :—calls the static function. Parameters for the function should be loaded onto the stack before this call.
pop :—pops a value from the stack. Used when we don't need to store a value in the variable.
ret :—returns from a function.
I will discuss about MSIL in my next article.
2 :- CLR(Comman Language Runtime) Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework.It is the implementation of CLI .The core runtime engine in the microsoft .net framework for executing assemblies. All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program. For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL, Java has Java Virtual Machine etc. Similarly .NET has CLR. Internet Exlorer is the example of hosting CLR. CLR have following qualities :-
Garbage Collection :- CLR automatically manages memory thus eliminating memory leaks. When objects are not referred GC automatically releases those memories thus providing efficient memory management.
Code Access Security :- CAS grants rights to program depending on the security configuration of the machine. Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file. CAS will take care that the code runs under the environment of machines security configuration.
Code Verification :- This ensures proper code execution and type safety while the code runs. It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.
IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL
code.
3 :- CTS(Comman Type System) :- In order that two language communicate smoothly CLR has CTS (Common Type System).Example
in VB you have “Integer” and in C++ you have “long” in c u have "int" these datatypes are not compatible so the interfacing between them is very complicated. In order to able that two different languages can 1. Basic .NET Framework communicate Microsoft introduced Common Type System. So “Integer” datatype in VB6 and
“int” datatype in C++ will convert it to System.int32 which is datatype of CTS. CLS which is covered in the coming question is subset of CTS.
4 :-CLS(Common Language Specification) :- This is a subset of the CTS which all .NET languages are expected to support. It was always a
dream of Microsoft to unite all different languages in to one umbrella and CLS is one step towards that. Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.
What are different types of JIT ?
In .net there are three type of JIT.JIT compiler is a part of the runtime execution environment.
Three JIT are following :-
Pre-JIT :- Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.
Econo-JIT :- Econo-JIT compiles only those methods that are called at runtime. However, these compiled methods are removed when they are not required.
Normal-JIT :- Normal-JIT compiles only those methods that are called at runtime.
These methods are compiled the first time they are called, and then they are stored in cache. When the same methods are called again, the compiled code from cache is
used for execution.
Three JIT are following :-
Pre-JIT :- Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.
Econo-JIT :- Econo-JIT compiles only those methods that are called at runtime. However, these compiled methods are removed when they are not required.
Normal-JIT :- Normal-JIT compiles only those methods that are called at runtime.
These methods are compiled the first time they are called, and then they are stored in cache. When the same methods are called again, the compiled code from cache is
used for execution.
What is Manifest in .net ?
An assembly manifest contains all the metadata.It means Assembly metadata is stored in Manifest and it needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes.Some points are given please go through it :-
1:- The assembly manifest can be stored in either a Portable Executable file an .exe or dll file with Microsoft intermediate language (MSIL) code or in a standalone Portable Executable file that contains only assembly manifest information.
These four items
1 :- assembly name
2 :- version number
3 :- culture
4 :- strong name information
These four make up the assembly's identity.
Assembly name: A string which specifying the assembly's name.
Version number: A major and minor version number, and a revision and build number. The clr uses these numbers to enforce version policy. Versioning concept is only applicable to global assembly cache (GAC) as private assembly lie in
their individual folders.
Culture: Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite assembly containing culture- or language-specific information.
Satellite Assembly :- An assembly with culture information is automatically assumed to be a satellite assembly.
Strong name information: The public key from the publisher if the assembly has been given a strong name.
List of all files in the assembly: A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the file containing the assembly manifest.
Type reference information: Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly.
Information on referenced assemblies: A list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.
1:- The assembly manifest can be stored in either a Portable Executable file an .exe or dll file with Microsoft intermediate language (MSIL) code or in a standalone Portable Executable file that contains only assembly manifest information.
These four items
1 :- assembly name
2 :- version number
3 :- culture
4 :- strong name information
These four make up the assembly's identity.
Assembly name: A string which specifying the assembly's name.
Version number: A major and minor version number, and a revision and build number. The clr uses these numbers to enforce version policy. Versioning concept is only applicable to global assembly cache (GAC) as private assembly lie in
their individual folders.
Culture: Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite assembly containing culture- or language-specific information.
Satellite Assembly :- An assembly with culture information is automatically assumed to be a satellite assembly.
Strong name information: The public key from the publisher if the assembly has been given a strong name.
List of all files in the assembly: A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the file containing the assembly manifest.
Type reference information: Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly.
Information on referenced assemblies: A list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.
How to view a Assembly of your code (What is ILDASM ?)

When it comes to understanding of internals nothing can beat ILDASM. ILDASM basically converts the whole exe or dll in to IL code. To run ILDASM you have to go to "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin". Note that i had v2.0 you have to probably change it depending on the type of framework version you have.
If you run IDASM.EXE from the path you will be popped with the IDASM exe program as
shown in figure ILDASM. Click on file and browse to the respective directory for the DLL whose assembly you want to view. After you select the DLL you will be popped with a tree view details of the DLL as shown in figure ILDASM. On double clicking on manifest you will be able to view details of assembly, internal IL code etc as shown in Figure Manifest View.
Note : The version number are in the manifest itself which is defined with the DLL or
EXE thus making deployment much easier as compared to COM where the information
was stored in registry. Note the version information in Figure Manifest view.
You can expand the tree for detail information regarding the DLL like methods etc