Feb 26, 2010

Changing color of a cell in datagrid and gridview contros in asp.net

In RowDataBound event of GridView

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].BackColor = System.Drawing.Color.Gray;
}
}

In OnItemDataBound event of DataGrid

protected void ItemDB(object sender, DataGridItemEventArgs e)
{

if (Convert.ToInt16 (e.Item.Cells[6].Text) >15 )
{
e.Item.Cells[6].ForeColor = System.Drawing.Color.Green;
}
else
{
e.Item.Cells[6].ForeColor = System.Drawing.Color.Red;
}
}
}

AJAX Basics

for Other browsers except IE

objXmlHttp=new XMLHttpRequest();

for > IE 6.0

objXmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

others

objXmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete

xmlhttp.onreadystatechange=function_name
xmlhttp.open("GET",url,true);
xmlhttp.send(null);

Feb 17, 2010

Authentication and Authorization in asp.net

authentication

1)windows authentication
-anonymous
-basic
-digest
-integrated windows
2)forms authentication
3)passport authentication
4)none

authorization

file authorization depends on NTFS permissions
url authorization depends on tag in web.config

forms authentication uses HTML forms to collect authentication information and check in databases. In forms tag
name="frmauth" loginURL="login.aspx" protection="all"

authorization
allow users="*/?"
deny users="*/?"
authorization

authentication mode="Forms"
forms loginUrl="Login.aspx" protection="All"
credentials passwordFormat="Clear"
user name="Admin" password="Admin"
user name="Super" password="Super"
user name="User" password="User"
credentials
forms
authentication


impersonation : by default not enabled
by default asp.net application runs under "aspnet" account. to run under specific user credentials require impersonation.

Anonymous Authentication: IIS doesn't perform any authentication check. IIS allows any user to access the ASP .NET application.

Basic Authentication: For this kind of authentication, a Windows user name and password have to be provided to connect. However, this information is sent over the network in plain text and hence this is an insecure kind of authentication. Basic Authentication is the only mode of authentication older, non-Internet Explorer browsers support.

Digest Authentication: It is same as Basic Authentication but for the fact that the password is hashed before it is sent across the network. However, to be using Digest Authentication, we must use IE 5.0 or above.

Integrated Windows Authentication: In this kind of authentication technique, passwords are not sent across the network. The application here uses either the kerberos or challenge/response protocols to authenticate users. Kerberos, a network authentication protocol, is designed to provide strong authentication for client-server applications. It provides the tools of authentication and strong cryptography over the network to help to secure information in systems across entire enterprise.

Dotnet questions for experienced people

1. From constructor to destructor (taking into consideration Dispose() and the concept of non-deterministic finalization), what the are events fired as part of the ASP.NET System.Web.UI.Page lifecycle. Why are they important? What interesting things can you do at each?
2. What are ASHX files? What are HttpHandlers? Where can they be configured?
3. What is needed to configure a new extension for use in ASP.NET? For example, what if I wanted my system to serve ASPX files with a *.jsp extension?
4. What events fire when binding data to a data grid? What are they good for?
5. Explain how PostBacks work, on both the client-side and server-side. How do I chain my own JavaScript into the client side without losing PostBack functionality?
6. How does ViewState work and why is it either useful or evil?
7. What is the OO relationship between an ASPX page and its CS/VB code behind file in ASP.NET 1.1? in 2.0?
8. What happens from the point an HTTP request is received on a TCP/IP port up until the Page fires the On_Load event?
9. How does IIS communicate at runtime with ASP.NET? Where is ASP.NET at runtime in IIS5? IIS6?
10. What is an assembly binding redirect? Where are the places an administrator or developer can affect how assembly binding policy is applied?
11. Compare and contrast LoadLibrary(), CoCreateInstance(), CreateObject() and Assembly.Load().
12. Describe the difference between a Thread and a Process?
13. What is a Windows Service and how does its lifecycle differ from a “standard” EXE?
14. What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?
15. What is the difference between an EXE and a DLL?
16. What is strong-typing versus weak-typing? Which is preferred? Why?
17. What’s wrong with a line like this? DateTime.Parse(myString
18. What are PDBs? Where must they be located for debugging to work?
19. What is cyclomatic complexity and why is it important?
20. Write a standard lock() plus double check to create a critical section around a variable access.
21. What is FullTrust? Do GAC’ed assemblies have FullTrust?
22. What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?
23. What does this do? gacutil /l find /i “about”
24. What does this do? sn -t foo.dll
25. What ports must be open for DCOM over a firewall? What is the purpose of Port 135?
26. Contrast OOP and SOA. What are tenets of each
27. How does the XmlSerializer work? What ACL permissions does a process using it require?
28. Why is catch(Exception) almost always a bad idea?
29. What is the difference between Debug.Write and Trace.Write? When should each be used?
30. What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?
31. Does JITting occur per-assembly or per-method? How does this affect the working set?
32. Contrast the use of an abstract base class against an interface?
33. What is the difference between a.Equals(b) and a == b?
34. In the context of a comparison, what is object identity versus object equivalence?
35. How would one do a deep copy in .NET?
36. Explain current thinking around IClonable.
37. What is boxing?
38. Is string a value type or a reference type?

Dotnet interview questions - FAQ's

1. What is CLR, CTS, CLS?
2. What is MSIL , IL ?
3. What are the new features of Framework 1.1?



Assembly

4. What is Assembly?
5. What are the contents of assembly?
6. What are the different types of assemblies?
7. What is the difference between a private assembly and a shared assembly?
8. What are Satellite Assemblies? How you will create this? How will you get the different language strings?
9. How will u load dynamic assembly? How will create assemblies at run time?
10. What is Assembly manifest? what all details the assembly manifest will contain?
11. Difference between assembly manifest & metadata?
12. What is Global Assembly Cache (GAC) and what is the purpose of it? (How to make an assembly to public? Steps) How more than one version of an assembly can keep in same place?
13. Advantage of ADO.Net?
14. How would u connect to database using .NET?
15. What are relation objects in dataset and how & where to use them?
16. Difference between OLEDB Provider and SqlClient ?
17. What are the different namespaces used in the project to connect the database? What data providers available in .net to connect to database?
18. Difference between DataReader and DataAdapter / DataSet and DataAdapter?
19. Which method do you invoke on the DataAdapter control to load your generated dataset with data?
20. Explain different methods and Properties of DataReader which you have used in your project?
21. What happens when we issue Dataset.ReadXml command?
22. In how many ways we can retrieve table records count? How to find the count of records in a dataset?
23. How to check if a datareader is closed or opened?IsClosed()
24. What happens when u try to update data in a dataset in .NET while the record is already deleted in SQL SERVER as backend?
OR What is concurrency? How will you avoid concurrency when dealing with dataset? (One user deleted one row after that another user through his dataset was trying to update same row. What will happen? How will you avoid the problem?)
25. How do you merge 2 datasets into the third dataset in a simple manner? OR If you are executing these statements in commandObject. "Select * from Table1;Select * from Table2”
26. how you will deal result set? How do you sort a dataset?If a dataset contains 100 rows, how to fetch rows between 5 and 15 only?
27. Differences between dataset.clone and dataset.copy?
28. What is the use of parameter object?
29. How do u implement locking concept for dataset?
30. How to generate XML from a dataset and vice versa?
31. What is method to get XML and schema from Dataset? getXML() and get Schema ()
32. If I have more than one version of one assemblies, then how'll I use old version (how/where to specify version number?)in my application?
33. How to find methods of a assembly file (not using ILDASM)
34. What is Garbage Collection in .Net? Garbage collection process?
35. What is Reflection in .NET? Namespace? How will you load an assembly which is not referenced by current assembly?
36. What is Custom attribute? How to create? If I'm having custom attribute in an assembly, how to say that name in the code?
37. How Garbage Collector (GC) Works?

38. Why do we need to call CG.SupressFinalize?
39. What is nmake tool?
40. What are Namespaces?
41. What is JIT (just in time)? how it works?
42. What is strong name?
43. What is portable executable (PE)?
44. What is Event - Delegate? clear syntax for writing a event delegate
45. Which namespace is the base class for .net Class library?
46. What are object pooling and connection pooling and difference? Where do we set the Min and Max Pool size for connection pooling?
47. What is exception handling?
48. What is the managed and unmanaged code in .net?
49. How do you create threading in .NET? What is the namespace for that?
50. Serialize and MarshalByRef?
51. using directive vs using statement
52. Describe the Managed Execution Process?
53. What is Active Directory? What is the namespace used to access the Microsoft Active Directories? What are ADSI Directories?
54. What is the difference between CONST and READONLY?
55. What is the difference between ref & out parameters?
56. What is the difference between Array and LinkedList?
57. What is the difference between Array and Arraylist?
58. What is Jagged Arrays?
59. What are indexers?
60. What is Asynchronous call and how it can be implemented using delegates?
61. How to create events for a control? What is custom events? How to create it?
62. If you want to write your own dot net language, what steps you will u take care?
63. Describe the difference between inline and code behind - which is best in a loosely coupled solution?
64. how dot net compiled code will become platform independent?
65. without modifying source code if we compile again, will it be generated MSIL again?



(COM)

66. Interop Services?
67. How does u handle this COM components developed in other programming languages in .NET?
68. What is RCW (Runtime Callable Wrappers)?
69. What is CCW (COM Callable Wrapper)
70. How CCW and RCW is working?
71. How will you register com+ services?
72. What is use of ContextUtil class?
73. What is the new three features of COM+ services, which are not there in COM (MTS)?
74. Is the COM architecture same as .Net architecture? What is the difference between them?
75. Can we copy a COM dll to GAC folder?
76. What is Pinvoke?
77. Is it true that COM objects no longer need to be registered on the server?
78. Can .NET Framework components use the features of Component Services?

(OOPS)

79. What are the OOPS concepts?
80. What is the difference between a Struct and a Class?
81. Value type & reference types difference? Example from .NET. Integer & struct are value types or reference types in .NET?

82. What is Inheritance, Multiple Inheritance, Shared and Repeatable Inheritance?
83. What is Method overloading?
84. What is Method Overriding? How to override a function in C#?
85. Can we call a base class method without creating instance?
86. You have one base class virtual function how will call that function from derived class?
87. In which cases you use override and new base?

C# Language features

88. What are Sealed Classes in C#?
89. What is Polymorphism? How does VB.NET/C# achieve polymorphism?
90. In which Scenario you will go for Interface or Abstract Class?

91. Write one code example for compile time binding and one for run time binding? What is early/late binding?
92. Can you explain what inheritance is and an example of when you might use it?
93. How can you write a class to restrict that only one object of this class can be created (Singleton class)?

(Access specifiers)

94. What are the access-specifiers available in c#?
95. Explain about Protected and protected internal, “internal” access-specifier?

(Constructor / Destructor)

96. Difference between type constructor and instance constructor? What is static constructor, when it will be fired? And what is its use?
97. What is Private Constructor? and it’s use? Can you create instance of a class which has Private Constructor?
98. I have 3 overloaded constructors in my class. In order to avoid making instance of the class do I need to make all constructors to private?
99. Overloaded constructor will call default constructor internally?
100. What are virtual destructors?
101. Destructor and finalize
102. What is the difference between Finalize and Dispose (Garbage collection)
103. What is close method? How its different from Finalize & Dispose?
104. What is boxing & unboxing?
105. What is check/uncheck?
106. What is the use of base keyword? Tell me a practical example for base keyword’s usage?
107. What are the different .net tools which u used in projects?
108. Is goto statement supported in C#? How about Java?
109. What’s different about switch statements in C#?


(ASP.NET)

110. Asp.net and asp – differences?
111. How ASP and ASP.NET page works? Explain about asp.net page life cycle?
112. Order of events in an asp.net page? Control Execution Lifecycle?
113. What are server controls?
114. What is the difference between Web User Control and Web Custom Control?

(Session/State)

115. Application and Session Events
116. Difference between ASP Session and ASP.NET Session?
117. What is cookie less session? How it works?
118. How you will handle session when deploying application in more than a server?
119. Describe session handling in a webfarm, how does it work and what are the limits?
120. What method do you use to explicitly kill a users session?
121. What are the different ways you would consider sending data across pages in ASP (i.e between 1.asp to 2.asp)?
122. What is State Management in .Net and how many ways are there to maintain a state in .Net? What is view state?
123. What are the disadvantages of view state / what are the benefits?
124. When maintaining session through Sql server, what is the impact of Read and Write operation on Session objects? will performance degrade?
125. What are the contents of cookie?
126. How do you create a permanent cookie
127. What is ViewState? What does the "EnableViewState" property do? Why would I want it on or off?
128. Explain the differences between Server-side and Client-side code?
129. Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?
130. Which ASP.NET configuration options are supported in the ASP.NET implementation on the shared web hosting platform?
131. Briefly describe the role of global.asax?
132. How can u debug your .net application?
133. How do u deploy your asp.net application?
134. Where do we store our connection string in asp.net application?
135. Various steps taken to optimize a web based application (caching, stored procedure etc.)
136. How does ASP.NET framework maps client side events to Server side events.

(Security)

138. Security types in ASP/ASP.NET? Different Authentication modes?
139. How .Net has implemented security for web applications?
140. How to do Forms authentication in asp.net?
141. Explain authentication levels in .net ?
142. Explain autherization levels in .net ?
143. What is Role-Based security?
144. How will you do windows authentication and what is the namespace? If a user is logged under integrated windows authentication mode, but he is still not able to logon, what might be the possible cause for this? In ASP.Net application how do you find the name of the logged in person under windows authentication?
145. What are the different authentication modes in the .NET environment?
146. How do you specify whether your data should be passed as Query string and Forms (Mainly about POST and GET)
147. What is the other method, other than GET and POST, in ASP.NET?
148. What are validator? Name the Validation controls in asp.net? How do u disable them? Will the asp.net validators run in server side or client side? How do you do Client-side validation in .Net? How to disable validator control by client side JavaScript?
149. Which two properties are there on every validation control?

150. How do you use css in asp.net?
151. How do you implement postback with a text box? What is postback and usestate?
152. How can you debug an ASP page, without touching the code?
153. What is SQL injection?
154. How can u handle Exceptions in Asp.Net?
155. How can u handle Un Managed Code Exceptions in ASP.Net?
156. Asp.net - How to find last error which occurred?
157. How to do Caching in ASP?
158. What is the Global ASA(X) File?
159. Any alternative to avoid name collisions other then Namespaces.
160. Which is the namespace used to write error message in event Log File?
161. What are the page level transaction and class level transaction?
162. What are different transaction options?
163. What is the namespace for encryption?
164. What is the difference between application and cache variables?
165. What is the difference between control and component?
166. You ve defined one page_load event in aspx page and same page_load event in code behind how will prog run?
167. Where would you use an IHttpModule, and what are the limitations of any approach you might take in implementing one?
168. Can you edit data in the Repeater control? Which template must you provide, in order to display data in a Repeater control? How can you provide an alternating color scheme in a Repeater control? What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control?
169. What is the use of web.config? Difference between machine.config and Web.config?
170. What is the use of sessionstate tag in the web.config file?
171. What are the different modes for the sessionstates in the web.config file?
172. What is smart navigation?
173. In what order do the events of an ASPX page execute. As a developer is it important to undertsand these events?
174. How would you get ASP.NET running in Apache web servers - why would you even do this?
175. What tags do you need to add within the asp:datagrid tags to bind columns manually
176. What base class do all Web Forms inherit from?
177. How can we create pie chart in asp.net?
178. Is it possible for me to change my aspx file extension to some other name?
179. What is AutoEventWireup attribute for ?

(WEBSERVICE & REMOTING)

180. What is a WebService and what is the underlying protocol used in it?Why Web Services?
181. Are Web Services a replacement for other distributed computing platforms?
182. In a Webservice, need to display 10 rows from a table. So DataReader or DataSet is best choice?
183. How to generate WebService proxy? What is SOAP, WSDL, UDDI and the concept behind Web Services? What are various components of WSDL? What is the use of WSDL.exe utility?
184. How to generate proxy class other than .net app and wsdl tool?
185. What is a proxy in web service? How do I use a proxy server when invoking a Web service?
186. asynchronous web service means?
187. What are the events fired when web service called?
188. How will do transaction in Web Services?
189. How does SOAP transport happen and what is the role of HTTP in it? How you can access a webservice using soap?
190. What are the different formatters can be used in both? Why?.. binary/soap
191. How you will protect / secure a web service?
192. How will you expose/publish a webservice?
193. What is disco file?
194. What’s the attribute for webservice method? What is the namespace for creating webservice?
195. What is Remoting?
196. Difference between web services & remoting?
197. Can you pass SOAP messages through remoting?
198. CAO and SAO.
199. singleton and singlecall.
200. What is Asynchronous Web Services?
201. Web Client class and its methods?
202. Flow of remoting?
203. What is the use of trace utility?

(XML)

204. Explain the concept of data island?
205. How to use XML DOM model on client side using JavaScript.
206. What are the ways to create a tree view control using XML, XSL & JavaScript?
207. Questions on XPathNavigator, and the other classes in System.XML Namespace?
208. What is Use of Template in XSL?
209. What is “Well Formed XML” and “Valid XML”
210. How you will do SubString in XSL
211. Can we do sorting in XSL ? how do you deal sorting columns dynamically in XML.
212. What is “Async” property of XML Means ?
213. What is XPath Query ?
214. Difference Between Element and Node.
215. What is CDATA Section.
216. DOM & SAX parsers explanation and difference
217. What is GetElementbyname method will do?
218. What is selectnode method will give?
219. What is valid xml document? What a well formed xml document?
220. What is the Difference between XmlDocument and XmlDataDocument?
221. Explain what a DiffGram is, and a good use for one?
222. If I replace my Sqlserver with XML files and how about handling the same?
223. Write syntax to serialize class using XML Serializer?

(IIS)

224. In which process does IIS runs (was asking about the EXE file)
225. Where are the IIS log files stored?
226. What are the different IIS authentication modes in IIS 5.0 and Explain?
227. Difference between basic and digest authentication modes?
228. How to configure the sites in Web server (IIS)?
229. Advantages in IIS 6.0?
230. IIS Isolation Levels?

Controls

231. How will you do Redo and Undo in a TextControl?
232. How to implement DataGrid in .NET? How would u make a combo-box appear in one column of a DataGrid? What are the ways to show data grid inside a data grid for a master details type of tables? If we write any code for DataGrid methods, what is the access specifier used for that methods in the code behind file and why?
233. How can we create Tree control in asp.net?

Programming

234. Write a program in C# for checking a given number is PRIME or not.
235. Write a program to find the angle between the hours and minutes in a clock
236. Write a C# program to find the Factorial of n
237. How do I upload a file from my ASP.NET page?
238. How do I send an email message from my ASP.NET page?
239. Write a program to create a user control with name and surname as data members and login as method and also the code to call it. (Hint use event delegates) Practical Example of Passing an Events to delegates
240. How can you read 3rd line from a text file?

Feb 11, 2010

Diff between intersect and innerjoin in SQL Server?

- Innerjoin gives duplicate rows where as intersect is not
- Innerjoin + distinct keyword = intersect

Cursors in SQL Server

USE Northwind
GO

DECLARE @Counter INT
DECLARE @EmployeeID INT

DECLARE Employees_Cursor CURSOR FOR
SELECT EmployeeID FROM Employees

OPEN Employees_Cursor

FETCH NEXT FROM Employees_Cursor into @EmployeeID

WHILE @@FETCH_STATUS = 0
BEGIN
SELECT * FROM Orders WHERE EmployeeID = @EmployeeID
FETCH NEXT FROM Employees_Cursor into @EmployeeID
END

CLOSE Employees_Cursor
DEALLOCATE Employees_Cursor

Some basics in SQL Server

SET ROWCOUNT 1000
SET NOCOUNT ON

Randomly taking records from a table
Select empname, newID() Randomcol from emp where empid=1 order by newID()

@@Rowcount – is used to find number of rows effected by a sql statement
Select @@Rowcount AS rowcount

TO FIND THE 3RD HIGHEST SAL IN EMP TABLE

select max(sal) from emp where sal not in(select distinct
top 2 sal from emp order by sal desc)

Normal Forms in SQL Server

First Normal Form (1NF)

First normal form (1NF) sets the very basic rules for an organized database:
• Eliminate duplicative columns from the same table.
• Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).

Second Normal Form (2NF)

Second normal form (2NF) further addresses the concept of removing duplicative data:
• Meet all the requirements of the first normal form.
• Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
• Create relationships between these new tables and their predecessors through use of foreign keys.

Third Normal Form (3NF)

Third normal form (3NF) goes one large step further:
• Meet all the requirements of the second normal form.
• Remove columns that are not dependent upon the primary key.

Fourth Normal Form (4NF)

Finally, fourth normal form (4NF) has one additional requirement:
• Meet all the requirements of the third normal form.
• A relation is in 4NF if it has no multi-valued dependencies.

ASP.Net Page life cycle - simple overview

Page_Init - Initialization of the page
LoadViewState - Loading of the View State
LoadPostData - processing of the Post back data
Page_Load - Loading of Page
RaisePostDataChangedEvent - Notification of PostBack
RaisePostBackEvent - Handling of PostBack Event
Page_PreRender - Pre Rendering of Page
SaveViewState - Saving of view state
Page_Render - Rendering of Page
Page_UnLoad - Unloading of the Page

Difference between sqlserver 2000 and sqlserver 2005

- In SQL Server 2000 the Query Analyzer and Enterprise Manager are seperate,whereas in SQL Server 2005 both were combined as Management Studio.
- In Sql 2005,the new datatype XML is used,whereas in Sql 2000 there is no such datatype
- In Sql server2000 we can create 65,535 databases,whereas in Sql server2005 2(pow(20))-1 databases can be created.

Events in GridView control of ASP.NET

For Edit
void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
myGridView.EditIndex = e.NewEditIndex;
BindData();
}

//

For Cancel
void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
myGridView.EditIndex = -1;
BindData();
}

For Update
void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = myGridView.Rows[e.RowIndex];
if (row != null)
{
TextBox t = row.FindControl("TextBox1") as TextBox;
if (t != null)
{
Response.Write("The Text Entered is" + t.Text);
}
}

For Select
void myGridView_SelectedIndexChanged(object sender, EventArgs e)
{
// This will contain the selectedValue of the row
string selectedCategory = myGridView.SelectedRow.Cells[1].Text;
}

For paging
void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
myGridView.PageIndex = e.NewPageIndex;
BindData();
}

// In Datagrid
OnPageIndexChanged ="PageData"
protected void PageData(Object source, DataGridPageChangedEventArgs e )
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
Binddata();
}

Delegates in C# - Simple Explanation

Delegates
=========

- also referred to as a type safe function pointer
- Improves the performance an application
- Used to call a method asynchronously
- You should follow the same syntax as in the method
- Example on multicast delegates:
delegate void Delegate_Multicast(int x, int y);
Class Class2
{
static void Method1(int x, int y)
{
Console.WriteLine("You r in Method 1");
}

static void Method2(int x, int y)
{
Console.WriteLine("You r in Method 2");
}

public static void "on" />Main()
{
Delegate_Multicast func = new Delegate_Multicast(Method1);
func += new Delegate_Multicast(Method2);
func(1,2); // Method1 and Method2 are called
func -= new Delegate_Multicast(Method1);
func(2,3); // Only Method2 is called
}
}

Difference between abstract classes and interfaces in C#

Abstract Classes

- In abstract class a method must be declared as abstract
- For abstract methods there will be no body
- The Abstract methods can delare with Access modifiers(public,internal,protected etc)But when implementing in subclass same access modifier we have to use.
- The Abstract class can contain variables and concrete methods
- Multiple inheritance is not possible
- must and should call all the abstract methods in the derived class
- To implement abstract method in derived class we have to use override keyword
- The accessmodifiers and return types(like void,int etc) must be same in abstract method and in derived class method
- we cannot create an object to abstract classes


Interfaces

- For interface methods also there will be no body
- In Interfaces we cannot use any access modifiers.By default these methods are public.
- We cannot declare variables and concrete methods in interfaces
- Multiple inheritance is possible
- must and should call all the interface methods in the derived class
- To implement interface methods in derived class no need of override keyword
- The accessmodifiers and return types(like void,int etc) must be same in interface methods and in derived class methods
- we cannot create an object to interfaces

Feb 10, 2010

Using unsafe code in C# in easy manner

class ClassName
{

//pointer

unsafe int * ptr;

unsafe void MyMethod()
{
//you can use pointers here
}

}

To declare unsafe local variables in a method, you have to put them in unsafe blocks as the following:

static void Main()
{

//can't use pointers here

unsafe

{

//here you can declare and use pointer

}

//can't use pointers here
}

Example
=======

static void Main()
{

int var1 = 5;

unsafe
{

int * ptr1, ptr2;

ptr1 = &var1;

ptr2 = ptr1;

*ptr2 = 20;

}

Console.WriteLine(var1);
}

OUTPUE: 20

Feb 1, 2010

ADO.NET basics reference

- ADO.NET objects - Connection, Command, DataSet, DataReader, DataAdapter

- DataSet consists of a collection of tables, relationships, and constraints

- The GetChanges method of the DataSet object actually creates a second DataSet that contains only the changes to the data. This DataSet is then used by a DataAdapter (or other objects) to update the original data source.

- DataAdapter object works as a bridge between the DataSet and the source data(database)

- DataReader for forwardonly and readonly stream of data

- DataAdapter updates the data from dataset to Database using update, insert, delete command or by using SqlCommandBuilder which automatically generates the update commands.(Example4)

- SqlDataAdapter manages the connection itself, meaning it opens the connection and it closes the connection. If you
open the connection yourself, it detects this and it will not close the connection. You need to close the connection manually.

- SqlDataAdapter attach error messages to rows in a dataset by using RowError property(Example5). Then you can walk the error in a DataTable with the GetErrors() method. You can also test for errors using HasErrors.

- use RejectChanges on the DataSet, in which case the Row is restored.

- The SqlDataAdapter and SqlCommand are very similar, except for the Fill and Update methods. The Fill method fills the dataset, Update method takes changes from a DataSet and pushes them back into the database. This is accomplished by four commands specified on the DataAdapter. These commands are: SelectCommand, UpdateCommand, InsertCommand, and DeleteCommand. CommandBuilder object can generate these at run time based on a select statement. However, this run-time generation requires an extra round trip to the server to gather required metadata, so explicitly providing the insert, update, and delete commands at design time will result in better run-time performance.

- Filter Dataset using its select method
Ex: ds.Select("custname like 'Sri%'");


- Example1:

SqlConnection con=new SqlConnection(constring);
SqlCommand com=new SqlCommand();
SqlTransaction trans;
con.open();
com.Connection=con;
//Begin Transaction
trans=con.BeginTransaction();
com.Transaction=trans;
try
{
com.CommandText = "Delete from emp where empid=10";
com.ExecuteNonQuery();
com.CommandText = "Insert into emp(empid) values(10)";
com.ExecuteNonQuery();
trans.Commit();
}
catch(Exception e)
{
trans.Rollback();
}
finally
{
con.Close();
}

- Example2:

// Example using stored procedures-create, drop, in and out parameters
string spsql1="create procedure proc_name @name nchar(10), @id int out as select @id=empid from emp where empname=@name";
string spsql2="IF EXISTS ( select name from sysobjects where name='proc_name' and type='P') DROP PROCEDURE proc_name";
SqlConnection con=new SqlConnection(constring);
try
{
SqlCommand com1=new SqlCommand(spsql1,con);
SqlCommand com2=new SqlCommand(spsql2,con);
com2.ExecuteNonQuery();
com1.ExecuteNonQuery();

SqlCommand com3=new SqlCommand("proc_name",con);
com3.CommandType=CommandType.StoredProcedure;

SqlParameter params=null;
params=com3.Parameters.Add("@name", SqlDbType.NChar, 10);

// By default the parameter direction is input. So no need to specify the below statement.
params.Direction = ParameterDirection.Input;
com3.Parameters["@name"].value="ABCD";

params=com3.Parameters.Add("@id", SqlDbType.Int, 10);
params.Direction=ParameterDirection.Output;

com3.ExecuteNonQuery();

Console.WriteLine(com3.Parameters["@id"].value);
}
Catch(Exception e)
{

}
finally
{
con.Close();
}

- Example3:
//using dataset
string sqlstr="select * from emp";
SqlConnection con=new SqlConnection(constring);
try
{
SqlCommand com1=new SqlCommand(sqlstr,con);
SqlDataAdapter sa=new SqlDataAdapter(com1);
DataSet ds = new DataSet();
// we can use directly SqlDataAdapter as
// SqlDataAdapter sa=new SqlDataAdapter(sqlstr,con);
sa.fill(ds,"Emp");
foreach (DataRow dr in ds.Tables["Emp"].Rows)
{
Console.WriteLine(dr["empid"].ToString());
}
}
catch(Exception e)
{

}

- Example4:
//update using SqlDataAdapter and SqlCommandBuilder
string sqlstr1="select * from emp";
string sqlstr2="select * from dept";
SqlConnection con=new SqlConnection(constring);
try
{
SqlCommand com1=new SqlCommand(sqlstr1,con);
SqlCommand com2=new SqlCommand(sqlstr2,con);
SqlDataAdapter sa1=new SqlDataAdapter(com1);
SqlDataAdapter sa2=new SqlDataAdapter(com2);
DataSet ds = new DataSet();
DataRow dr;

// Create command builder. This line automatically generates the update commands for you, so you don't
// have to provide or create your own.
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(sa1);

// Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary
// key & unique key information to be retrieved unless AddWithKey is specified.
sa1.MissingSchemaAction = MissingSchemaAction.AddWithKey;
sa2.MissingSchemaAction = MissingSchemaAction.AddWithKey;


sa1.fill(ds,"Emp");
sa2.fill(ds,"Dept");

// ADD RELATION
ds.Relations.Add("empdept", ds.Tables[0].Columns["empid"], ds.Tables[1].Columns["empid"]);

// EDIT
ds.Tables[0].Rows[0]["empname"] = "Pinkoo";

// ADD
dr=ds.Tables[0].NewRow();
dr["empid"]=10;
dr["empname"]="simpy";
ds.Tables[0].Rows.Add(dr);

//Update Database with SqlDataAdapter
da1.Update(ds,"Emp");

}
catch(Exception e)
{

}

-Example5:
// Create a new dataview instance on the emp table that was just created
DataView myDataView = new DataView(myDataSet.Tables["emp"]);
// Sort the view based on the empname column
myDataView.Sort = "empname";
myDataSet.Tables["emp"].Rows[0].RowError = "An Error was added";
myDataSet.Tables["emp"].Rows[1].RowError = "This is another error message";
if (myDataSet.Tables["Customers"].HasErrors)
{
DataRow[] ErrDataRows = myDataSet.Tables["emp"].GetErrors();
for (int i = 0; i <= ErrDataRows.Length - 1; i++)
{
}
}

-Example6:
//using Relations in a dataset
string sqlstr1="select * from emp";
string sqlstr2="select * from dept";
SqlConnection con=new SqlConnection(constring);
try
{
SqlCommand com1=new SqlCommand(sqlstr1,con);
SqlCommand com2=new SqlCommand(sqlstr2,con);
SqlDataAdapter sa1=new SqlDataAdapter(com1);
SqlDataAdapter sa2=new SqlDataAdapter(com2);
DataSet ds = new DataSet();

sa1.fill(ds,"Emp");
sa2.fill(ds,"Dept");

// ADD RELATION
ds.Relations.Add("empdept", ds.Tables[0].Columns["empid"], ds.Tables[1].Columns["empid"]);

foreach (DataRow dr1 in ds.Tables[0].Rows)
{
//access dr1["empid"]
foreach (DataRow dr2 in dr1.GetChildRows(ds.Relations["empdept"]))
{
//access dr2["deptid"]
}
}