Quote for the Week

"Learn to enjoy every moment of your life"

Monday, August 25, 2014

C# Threading Concept in .Net

Thread :

A Thread is a unit of execution where every program has a thread to execute the program and we call it as "Main() Thread". So, by default every program is single threaded.

- In a single threaded application the execution of program takes place by performing the actions one after the other that is it will call the methods one by one. The Drawback in this approach is if a method is taking more time to execute then the expected time the other methods which has to execute next has to wait.

For example:

Main() Thread
 - Method1()
 - Method2()
 - Method3()

Multi-Threading:

-  A single application performing multiple actions at point of time simultaneously is know Multi- Threading.

-  we can overcome the above problem by using multi-threading where in this approach we have separate thread for each method to execute. When we use multi- thread in an application the execution of the programs will take place by adopting two principles.

1. Time sharing: where in this case the operating system allocates some time period for each thread to execute & transfer the controls to other threads once the given period elapses by giving equal importance for all methods to run.

2. Maximum utilization of Resource : This comes into picture when the time sharing violates i.e.., if the thread could not execute the some reason on its given time period without waiting at that method ideally that control gets transferred  to the other thread in execution.

T1 - > method1()
T2 - > method2()
T3 -> method3()

The main goal of multi-threading is maximum utilization of CPU resources.

How to Create Thread ??

If we want to create thread we need to create object of class 'thread' which is present under "System.Threading" namespace by parsing the method we want to call by thread as a parameter to the constructor of the class.

System.Threading.Thread(<method1()>);

Thread t1()=new Thread(method1()) ;
Thread t2()=new Thread(method2()) ;
Thread t3()=new Thread(method3()) ; 

Members of Thread class : 

1. Start() :

A Method which should call on the thread object we have created to start the execution of thread.

2. Abort() :

If this method is called on a thread object, it will terminate the execution of the thread in the middle of this execution.

3. Suspend()

If will pause the execution of a thread until resume() method is called.

4. Resume()

It resumes the execution of suspend thread.

5. Sleep(int milliseconds) 

It is a static method which will suspect the execution of current executing thread until the give time period elapses.

6. Join()

When this method is called on a thread object it will make the main() thread to wait without existing the program until the thread o which Join() is called.

7. Priority()

It is enumerated property using which can set the priorities between the threads in sharing the CPU resources

For Example:

using System;
using System.Threading;

class ThreadDemo
{
 Thread t1,t2,t3;
  public void ThreadDemo()
   {
      t1=new Thread( Method1);
      t2=new Thread( Method2);
      t3=new Thread( Method3);
      t1.Start();   t2.Start();   t3.Start();
   }

   public void Method1()
   {
      for(int i=1;i<=100;i++)
         {
             Console.WriteLine("Method1:"+i);
          }
         Console.WriteLine("Method1 is Exiting..");
   }
   public void Method2()
   {
      for(int i=1;i<=100;i++)
         {
             Console.WriteLine("Method2:"+i); 
            if(i==50)
            {
             Thread.Sleep(1000);
             }
          }
        Console.WriteLine("Method2 is exiting");
    }
   public void Method3()
   {
      for(int i=1;i<=100;i++)
         {
             Console.WriteLine("Method3:"+i);
          }
        Console.WriteLine("Method2 is exiting");
    }   
   public static Main()
   {
         ThreadDemo obj =new ThreadDemo();
         obj.t1.Join();
         obj.t2.Join();
         obj.t3.Join();
         Console.WriteLine("Main Thread is exiting");
    }

}


Summary:

What do you think? Do you like this Article? Want to know more interesting concepts in .Net, then Subscribe and Follow to this blog. Have a Good Day.








Sunday, August 24, 2014

Question raised by Sharath Kumar- "What is difference between == and .Equals?"

Question is raised by Sharath kumar by sending mail to dotnetcircle@gmail.com.

What is difference between == and .Equals?

My Answer:

When == is used on an object type, it'll resolve to System.Object.ReferenceEquals.

Equals is just a virtual method and behaves as such, so the overridden version will be used (which, for string type compares the contents).


Let's see by example:

In this example we assigned a string variable to another variable. A string is a reference type and in the following example, a string variable is assigned to another string variable so they are referring to the same identity in the heap and both have the same content so you get True output for both the == Operator and the Equals() method.

using System;
namespace ComparisionExample
{
    class Program
    { 
       static void Main(string[] args) 
       { 
           string name = "dotnetcircle"; 
           string myName = name; 
           Console.WriteLine("== operator result is {0}", name == myName);
            Console.WriteLine("Equals method result is {0}", name.Equals(myName));
            Console.ReadKey();
        }  
    }
}

o/p:

== operator result is True
.Equals method result is True

Let’s see another example where the contents will be the same in both object variables but both have different references. So the == Operator returns False because it compares the reference identity while the Equals() method returns True because it compares the contents of the objects.

using System;
namespace ComparisionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            object name = "dotnet";
            char[] values = {'d','o','t','n','e','t'};
            object myName = new string(values);         
            Console.WriteLine("== operator result is {0}", name == myName);
            Console.WriteLine("Equals method result is {0}", myName.Equals(name));
            Console.ReadKey();
        }     
    }
}

o/p:

== operator result is false
Equals method result is false.

For more clear,

StringBuilder s1 = new StringBuilder("fred");
StringBuilder s2 = new StringBuilder("fred");
Console.WriteLine( s1 == s2 );
Console.WriteLine( s1.Equals(s2) );
will display:

False
True


s1 and s2 are different objects (hence == returns false), but they are equivalent (hence Equals() returns true).

Unfortunately there are exceptions to these rules. The implementation of Equals() in System.Object (the one your class inherits by default) compares identity, i.e. it's the same as operator==. So Equals() only tests for equivalence if the class author overrides the method (and implements it correctly). Another exception is the string class - its operator== compares value rather than identity.


If you want to perform an identity comparison use the ReferenceEquals() method. If you want to perform a value comparison, use Equals() but be aware that it will only work if the type has overridden the default implementation. Avoid operator== with reference types (except perhaps strings), as it's simply too ambiguous.



Summary:

Do you know more clear answer? you can contribute with your answer in this blog by sending mail to dotnetcircle@gmail.com. 

Saturday, August 23, 2014

Important Interview Questions to know in Asp.net

Note:

Do you want answers? you can send a  request mail to dotnetcircle@gmail.com for Answers, if you need to know, we will forward you the Answers, please note that your mail account should be  follower and a subscriber to this blog.

1. What CLR Does?
2. Explain CTS (Common Type System)?
3. Explain CLS (Common Language Specification)
4. Explain Boxing and unboxing?
5. Explain Variables in C#.
6. Explain Jump statements in c#.
7. What is nullable Type?
8. Why does string in .net is immutable?
9. Explain string Comparison?
10. Explain String Interning?
11. Explain String Pooling?
12. Explain string builder functioning behind the scene?
13. Explain Indexers?
14. Explain Iterators?
15. Explain secure strings?
16. Explain Enumerated types.
17. Explain interface.
18. Should I design a base type or an interface?
19. Explain App domain?
20. Explain Threading in dot net?
21. What is diffgram?
22. How assignment of value is different in value type and reference type?
23. Difference between shallow copy and deep copy of object?
24. What is use of using keyword?
25. What is cloning?
26. What is Assembly? Difference between Private and Shared Assembly? How can we make shared assembly?
27. Why value type cannot be inherited?
28. What is the difference between an event and a delegate?
29. What size is .net object?
30. When and How to Use Dispose and Finalize in C#?
31. What is difference between equivalent of objects and identical of objects?
32. What's the difference between the System.Array.CopyTo() and System.Array.Clone()?
33. How ado.net maintain transaction of data?
34. What is delay signing?
35. Can you declare a C++ type destructor in C# like ~MyClass ()?
36. What is difference between == and .Equals?
37. What is the difference between structures and enumeration?
38. Should I make my destructor virtual?
39. How do I declare a pure virtual function in C#?
40. Where would you use an iHTTPModule, and what are the limitations of any approach you might take in implementing one?
41. What is difference between code base security and role base security? Which one is better?
42. Is it possible to prevent a browser from caching an aspx page?
43. What is the difference between Debug. Write and Trace. Write?
44. What is difference between repeater over datalist and datagrid?
45. Describe Main Characteristics of static functions?
46. What is DataReader? Difference between datareader and dataset?
47. What is DLL hell?
48. What is Temporary Table? How can we create it?
49. What is strong key and what is the use of it?
50. What is Impersonation?
51. What is Partitioned Tables?
52. What types of data validation events are commonly seen in the client-side form validation? Web service support?
54. What is PreProcessor in .NET and type , where it use?
55. Please brief not about XSD, XSLT & XML?
57. What is Polymorphism?
58. What is implicit operator overloading?
59. What is Operator Overloading?
60. What is difference between http handler and http module?
61. What is Caching? Where is it use? Why and when?
62. What is Cursor? Define Different type of cursor?
63. What is Views?
64. What is Triggers? What are the different types of triggers in Sql Server 2005?
65. What is use of extern keyword?
66. What is base assembly of Dot net?
67. What’s difference between Shadowing and Overriding?
68. What’s difference between Server.Transfer and response.Redirect?
69. Can you explain in brief how the ASP.NET authentication process works?
70. What are the various ways of authentication techniques in ASP.NET?
71. How does authorization work in ASP.NET?
72. What’s difference between Datagrid, Datalist and repeater?
73. What exactly happens when ASPX page is requested from Browser?
74. What is the result of ―select firstname, secondname from emp order by 2‖?
75. How can we create proxy class without VS?
76. How can we create overloaded methods in Web Service?
77. How can we maintain State in WebService?
78. ASP.Net Page Life Cycle ?
79. What are the different data types in dot net?
80. What is Static class?
81. How can you increase SQL performance?
82. What is ACID fundamental and what are transactions in SQL SERVER?
83. If we have multiple AFTER Triggers on table how can we define the sequence of the triggers?
84. Give the output of following code ?
85. Give the output of following code?
86. Give output of following code?
87. What is Performance tips and tricks in .net application?
88. How Garbage Collector Works?
89. How objects are allocated on heap?
90. What causes finalize methods to be called?
91. What is Sync Block Index and object pointer?
92. What is JIT compiler? What is its role?
93. How Types are stored in dot net?
94. Explain structure of GAC in windows?
95. What is Advantage and disadvantage of GC?
96. What is Reflection? Explain about reflection performance
97. What are members of a type?
98. Explain bridge between ISAPI and Application Domains?
99. How Securely Implement Request Processing, Filtering, and Content Redirection with HTTP Pipelines in ASP.NET?
100. Is there any difference in the way garbage collection works when it is called automatically by the Runtime
environment, and when it is invoked intentionally by the programmer?
101. What is probing?
102. What is compilation and execution procedure for asp.net page?
103. If need an array of objects then which option when better ArrayList Class or List Generic Class ? Array[] / ArrayList / List<T> Difference i.e. string[] arraylist.add(string) / List<string> ?
104. Custom Paging in ASP.NET 2.0 with SQL Server 2005
106. What is the difference between a Struct and a Class?
108. What is Web Gardening? How would using it affect a design?
109. What is view state? Where it stored? Can we disable it?
110. Can you debug a Windows Service? How?
111. What are the different ways a method can be overloaded?
112. How do you handle data concurrency in .NET?
114. What are jagged array?
115. Who host CLR? How windows identify where running assembly is managed or not?
116. Conceptual view of DotNet Framework
117. Explain Delegates?
118. Explaint about Events?
119. How to: Connect Event Handler Methods to Events ?
120. How to: Consume Events in a Web Forms Application ?
121. What’s the difference between localization and globalization?
122. Difference between primitive types, ref types and value types?
123. Difference between gettype() and typeof
124. What is Microsoft SharePoint Portal Server?
127. What is difference between static and singleton classes?
128. Explain Advantages of WCF.
129. What is dependency Injection?
130. What is difference between STA & MTA?
132. How does a database index work? 178
133. Give some threading best practices?
134. What is object pooling?
135. Static and Dynamic Assembly.
136. Why we have to consider object in lock statement as private?
137. How can we make class immutable? Give Example
138. How to override Equal, GetHashCode?
139. What is SSL and how can we implement it in our asp.net website?
140. What is difference between runtime polymorphism and compile time polymorphism?
141. What is difference between real proxy and transparent proxy?
142. What is prologue code?
143. Explain string class or what is behind the scene of string?
144. What is Encapsulation, polymorphism and abstraction? Give real time examples?
145. Why we use command object?
146. What is Satellite Assembly? How application knows which assembly should be loaded for particular culture?
147. Http request and response life cycle in ASP.Net?
148. If any body is editing data in webpage and at the time of editing row has been explicitly locked by user but if
any one stop website processing then how will handle locking?
149. Applied use of Inheritance ( i.e aggregation, specialization etc)
150. Explaing Connection pooling
151. Difference between dbnull and null?
152. What is snapshot in sql server?



Friday, August 22, 2014

WPF Architecture - An overview of Windows Presentation Foundation (WPF) Architecture

In this article we are going to see an overview of Windows Presentation Foundation. In previous WPF tutorial i have explained a basic introduction to WPF. I would suggest to read that article because it explains why Microsoft introduced WPF and how it is better than Windows Forms applications.

To know more about the Windows Presentation Foundation(WPF), one must have a clear idea about the architecture of WPF. So lets get some overview of wpf architecture.


Overview of Windows Presentation Foundation

----------------------------------------------------------------------------------------


Windows Presentation Framework is a next generation UI framework to create applications with a rich user experience. It is part of the .NET framework 3.0 and higher. WPF architecture is a layered architecture which have Managed, Unmanaged and Core API layers as shown in below fig.



The position of WPF within the .NET Framework.


01. Managed Layer

Managed layer has two main components – Presentation Framework and Presentation Core.

- Presentation Framework provides the required functionalities that we need to build the WPF applications such as controls, data bindings, styling, shapes, media, documents, annotations, animation and more. PresentationFamework.dll is responsible for this purpose.

- Presentation Core acts as a managed wrapper around MILCore and provides public interface for MIL. Presentation Core is the home for WPF Visual System and provides classes for creating application visual tree. The Visual System creates visual tree which contains applications Visual Elements and rendering instructions. PresentationCore.dll is responsible for this purpose.



                  The public API exposed is only via this layer. Major portion of the WPF is in managed code.

PresentationFramework.dll :- It holds the top level WPF elements, including those that represents Windows, panels, controls, styles etc. It also implements the end-user presentation features including time-dependent, story-based animations and data binding.

PresentationCore.dll :- Presentation Core provides a managed wrapper for MIL and implements the core services for WPF such as UI Element and visual from which all shapes and controls derived in PresentationFramework.dll.

WindowsBase.dll :- Holds more basic elements which are capable to be reused outside the WPF environment like Dispatcher objects and Dependency objects.

02. Unmanaged Layer

This layer is also called milcore or Media Integration Library Core. MilCore is written in unmanaged code in order to enable tight integration with DirectX. DirectX engine is underlying technology used in WPF to display all graphics, allowing for efficient hardware and software rendering. MIL has Composition System that receives rendering instructions from Visual System and translates into data that can be understood by DirectX to render user interface.

03. Core API Layer

This layer has OS core components like Kernel, User32, GDI, Device Drivers, Graphic cards etc. These components are used by the application to access low level APIs. User32 manages memory and process separation.


Summary :

Do you like this Article? want to know more Interesting things on .Net, then you can subscribe and follow to this blog.



Thursday, August 21, 2014

Connecting with Different Database Servers in .Net

Today, we will see how to connect with Different Databases in Ado.Net Framework.

1. For  SQL Server

Using ODBC
-------------

 // ODBC -- Standard Connection
using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={SQL Server}; Server=ServerName; DataBase=DataBaseName; Uid=UserName; Pwd=Secret";
conn.Open();

 // ODBC -- Trusted Connection
using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={SQL Server}; Server=ServerName; DataBase=DataBaseName; Uid=admin; Pwd=password";
conn.Open();
// or

OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={SQL Server}; Server=ServerName; DataBase=DataBaseName; Trusted_Connection=Yes;";
conn.Open();

Using OLEDB
---------------------

 // OleDb -- Standard Connection
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=SQLOLEDB; Data Source=ServerName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;";
conn.Open();
 // OleDb -- Trusted Connection
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=SQLOLEDB; Data Source=ServerName; Initial Catalog=DataBaseName; Integrated Security=SSPI;";
conn.Open();

Using .Net DataProvider
------------------------------

 // .NET DataProvider -- Standard Connection
using System.Data.SqlClient;
SqlConnection conn = new SqlDbConnection();
conn.ConnectionString ="Data Source=ServerName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;";
conn.Open();
 // .NET DataProvider -- Trusted Connection
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=ServerName; Initial Catalog=DataBaseName; Integrated Security=SSPI;";
conn.Open();

2. For Oracle

Using ODBC
---------------------

 // ODBC -- New Microsoft Driver

using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={Microsoft ODBC for Oracle};Server=OracleServer.world;Uid=UserName;Pwd=Secret;";
conn.Open();

 // ODBC -- Oracle Driver

using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={Oracle ODBC Driver};Dbq=myDataBase;Uid=UserName;Pwd=Secret;";
conn.Open();

Using OLEDB

 // OleDb -- Oracle Driver -- Standard Connection
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=OraOLEDB.Oracle;Data Source=ServerName;User id=UserName;Password=Secret;";
conn.Open();

 // OleDb -- Oracle Driver -- Trusted Connection
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=OraOLEDB.Oracle;Data Source=ServerName;OSAuthent=1;";
conn.Open();
// or
using System.Data.OleDb;

OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=OraOLEDB.Oracle;Data Source=ServerName;User id=admin;Password=pwd";
conn.Open();

3. For DB2

Using ODBC
-------------
 // ODBC without DSN
using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={IBM DB2 ODBC DRIVER};DataBase=DataBaseName; HostName=ServerName; Protocol=TCPIP;Port=PortNumber;Uid=UserName;Pwd=Secret";
conn.Open();

Using OLEDB
--------------

 // OleDb -- Microsoft Driver
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=DB2OLEDB; Network Transport Library=TCPIP; Network Address=xxx.xxx.xxx.xxx; Package Collection=CollectionName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;";
conn.Open();

// OleDb -- IBM Driver
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=IBMDADB2; DataBase=DataBaseName; HostName=ServerName; Protocol=TCPIP; Port=PortNumber; Uid=UserName; Pwd=Secret;";
conn.Open();

Using .Net DataProvider
-----------------------
 // .NET DataProvider from IBM
using IBM.Data.DB2;
Db2Connection conn = new Db2Connection();
conn.ConnectionString = "DataBase=DataBaseName;Uid=UserName;Pwd=Secret";

conn.Open();

4. For MySQL

Using ODBC
------------
 // ODBC -- MyODBC Driver -- remote database
using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={MySql}; Server=db.domain.com; Option=131072; Port=3306; Stmt=; DataBase=DataBaseName; Uid=UserName; Pwd=Secret;" ;
conn.Open();

Using OLEDB
------------
 // OleDb
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=MySqlProv; Data Source=ServerName; User id=UserName; Password=Secret";
conn.Open();

Using .Net DataProvider
------------------------

 // .NET DataProvider from CoreLab
using CoreLab.MySql;
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString ="Host=ServerName; DataBase=DataBaseName; Protocol=TCP; Port=3306; Direct=true; Compress=false; Pooling=true; Min Pool Size=0; Max Pool Size=100; Connection Lifetime=0; User id=UserName;Password=Secret";

conn.Open();

5. For Microsoft Access

Using ODBC
--------------
 // ODBC -- Standard Security
using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)}; Dbq=c:\myPath\myDb.mdb; Uid=Admin; Pwd=;password";
conn.Open();

 // ODBC -- Workgroup (System Database)
using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)}; Dbq=c:\myPath\myDb.mdb; SystemDb=c:\myPath\myDb.mdw;";
conn.Open();

Using OLEDB
-------------

 // OleDb with MS Jet -- Standard Security
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\mypath\myDb.mdb; User id=admin;Password=password";
conn.Open();
 // OleDb with MS Jet -- Workgroup (System Database)
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\mypath\myDb.mdb; System Database=c:\mypath\myDb.mdw";
conn.Open();


Summary :

Do you like this Article? Want to know more Interesting Concepts in .Net, then Subscribe and Follow to this blog.

Tuesday, August 12, 2014

SQL Server Basics of Cursors

CURSOR :

Cursor is a pointer to the temporary memory where data is retrieved from a table is stored. Main purpose of cursor is to provide access to one by one row in sequence from a table.

To work with cursor you have to perform the following five steps:

1. Cursor Declaration :

The first step to work with cursor is declaring the cursor. In cursor declaration you have to provide a name to the cursor, type of cursor and associate a 'select' statement to the cursor.

syntax: 

declare <cursor name> Cursor
[local/global]
[forwared-only/scroll]
[static/dynamic/keyset]
for [select statement]

2. Opening Cursor:

When we open the cursor then the select statement associated with cursor will be executed, rows retrieved by SELECT will be stored in temporary memory & CURSOR will point to that memory.

syntax:

OPEN <cursor name>

3. Fetching Data from Cursor :

When you have to make any changes to the data available in Cursor, you must copy the data from Cursor into variables in the program & this process of copying data from cursor into variables in the program is called Fetching Data.

Syntax: 

fetch  nexy/prior/first/last/relative/
absolute<n> from <cursor name> into
<local variable list>

After fetching a row to verify whether or not the fetch statement successfully fetches a row, use system variable "@@FETCH_STATUS". This variable will contain the value zero when 'fetch' was Success.

0 - fetch was success
1 - if the row try to fetch was beyond cursor.
2 - if the row try to fetch was missing in cursor.

4. Closing Cursor

After accessing data from cursor is completed you can close the cursor, when you close then link to temporary memory from your program will be closed, but the memory allocated for the cursor will not de-allocated. Hence, you can reopen the cursor.

syntax: Close <cursor name>

5. De-allocating Cursor

You can de-allocate the complete memory allocated for the cursor & once the cursor is de-allocated you can reopen the cursor without executing declaration statement again.

Syntax:

Deallocate <cursor name>

Simple Example for Cursor :

 CREATE TABLE Employee
(
 EmpID int PRIMARY KEY,
 EmpName varchar (50) NOT NULL,
 Salary int NOT NULL,
 Address varchar (200) NOT NULL,
)
GO
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(1,'Mohan',12000,'Noida')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(2,'Pavan',25000,'Delhi')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(3,'Amit',22000,'Dehradun')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(4,'Sonu',22000,'Noida')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(5,'Deepak',28000,'Gurgaon')
GO
SELECT * FROM Employee 




SET NOCOUNT ON
DECLARE @Id int
DECLARE @name varchar(50)
DECLARE @salary int
DECLARE cur_emp CURSOR
STATIC FOR 
SELECT EmpID,EmpName,Salary from Employee
OPEN cur_emp
IF @@CURSOR_ROWS > 0
BEGIN 
FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
WHILE @@Fetch_status = 0
BEGIN
PRINT 'ID : '+ convert(varchar(20),@Id)+', Name : '+@name+ ', Salary : '+convert(varchar(20),@salary)
FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
END
END
CLOSE cur_emp
DEALLOCATE cur_emp
SET NOCOUNT OFF 




Summary:

What do you think about this Article?

Please give feedback to dotnetcircle@gmail.com

For any queries, ideas or any other mail to dotnetcircle@gmail.com


Saturday, August 9, 2014

New Learners: Understanding Normalization in SQL Server


What is Normalization?

When we want to store the some piece of information, we store it in database. Now storing a data in database mean, it should be stored properly so that while retrieving it, it should be easy. So we say store it in Normalized way. In short, Normalization can be defined as the process of organizing the data in database efficiently. The result of normalization is a logical database design and is called as Normal Form.

Why Normalization?
Goals of Normalization process are:

 -  It helps you to eliminate the redundant data from same table.
 -  It ensures the data dependencies between the tables are proper.
 -  A Normalized database design makes it easy to change in modification is required.

Advantages of Normalization

 - Data redundancy is removed
 - Faster update as redundant columns from a tables are removed.
 - Easy understanding of structure
 - Improvement in Index as be achieved
 - Long term maintainability of database get easier

Disadvantages of Normalization

 - Query to some extent get complicated
 - Performance may degrade due to multiple joins
 - Suppose I have some data with me, say


As you can see above, table is not properly managed

Normalization process is mainly divided in to stages which we call as Normal Form. Let’s talk about each Normal Form one by one with an example. Basically a database can be normalized into various normal forms such as-

1. First Normal Form (1NF)
2. Second Normal Form (2NF)
3. Third Normal Form (3NF)
4. Boyce Codd Normal Form (BCNF)
and Fourth Normal Form (4NF) and so on.

But today I would like to talk about only up to Boyce Codd Normal Form because Fourth Normal Form and others is rarely used in the database design.

First Normal Form (1NF)

It says,
 - Eliminate all repeating groups in individual table
 - One cell should contain only one data
 - Create a separate table for each set of related data
 - Identify each set of related data with a primary key


As you can see above,

 -  Our UnNormalized table does not have repeating group. So this is not applicable over here.
 - We have eliminated the comma separated values and shifted to another table Skill. Each employee in Employee table is related to Skill table through EmployeeId column (Note: It is not a foreign key relationship.  -  We are just replacing the comma separated values in each cell in to rows and creating separate table for it).
 -  Each cell is containing single value.
 -  Skills of table is identified with primary key.

Second Normal Form (2NF)

It says,

 - Tables should be in First Normal Form (1NF)
 - Eliminate partial primary key dependencies
 - Non key column must depend on the entire composite primary key and create separate tables for sets of       values that apply to multiple records.
 - Relate these tables with a foreign key


As you can see above,
 - We have eliminated the partial primary key dependency of EmployeeId and created a new table which will contain the relation of EmployeeId and SkillId. This both columns will be the respective foreign key for Employee and Skill table.

Third Normal Form (3NF)

- Table should be in Second Normal Form
- Eliminate fields that are not dependent on key i.e. - Eliminate Transitive Dependencies. Create a separate table for it.
- Let’s suppose I want to add new columns in Employee Table Manager and Project.


Now, adding this 2 column violates the third Normal Form because the non key column Project is dependent on another not key column i.e. - Manager.
So we will normalize the table by separating nondependent column to another table. This way we can achieve third Normal Form.



Boyce Codd Normal Form (BCNF)
It says,

 - BCNF is based on the concept of a determinant.
 - A determinant is any attribute (simple or composite) on which some other attribute is fully functionally dependent.
 - A relation is in BCNF is, and only if, every determinant is a candidate key.
 - The same as 3NF except in 3NF we only worry about non-key attributes

Note: If there is only one candidate key then 3NF and BCNF are the same.

Consider another column in below table say ProjectTechnology



- As shown above, each manager will be handling unique project, so we can say particular project is determined by particular manger where Manager and Project depicts a candidate key.

- If we delete the entry of Manager Ronnie from the table we lose not only information of Project BCF but also the fact that project was developed in Asp.Net technology. We cannot make the entry of the fact that BCF project was developed using Asp.Net.

So let’s break this into separate tables


Fourth Normal Form (4NF)

It says,

 - Database design should follow the 1NF, 2NF, 3NF and BCNF if possible
 - There must not be more than one multivalued dependencies other than a candidate key.
 - I hope you got it what actually is the process of Normalization.

Conclusion

Thus concluding it, Normalization is a process which is a must to design any database. Hope you like this article. Please share your comments whether it’s good or bad. Your comments are valuable to me to get better. 

Friday, August 8, 2014

Learners: Exceptions Handling in C#.Net

Exceptions:
--------------


An Exception is an object delivered by the Exception class. This Exception class is exposed by the System.Exception namespace. Exceptions are used to avoid system failure in an unexpected manner. Exception handles the failure situation that may arise. All the exceptions in the .NET Framework are derived from the System.Exception class.

To understand exception, we need to know two basic things:

1. Somebody sees a failure situation that happened and throws an exception by packing the valid information.

2. Somebody who knows that a failure may happen catches the exception thrown. We call it Exception Handler.

In other words, Exception objects that describe an error are created and then thrown with the throw keyword. The runtime then searches for the most compatible exception handler.

Programmers should throw exceptions when:

- The method cannot complete its defined functionality. For example, if a parameter to a method has an invalid value:

static void CopyObject(SampleClass original)
{
    if (original == null)
    {
        throw new System.ArgumentException("Parameter cannot be null", "original");
    }

}

This type of Exception is thrown as ArgumentNullException.

- An inappropriate call to an object is made, based on the object state. For example, trying to write to a read-only file. In cases where an object state does not allow an operation, throw an instance of InvalidOperationException or an object based on a derivation of this class. This is an example of a method that throws an InvalidOperationException object:

class ProgramLog
{
    System.IO.FileStream logFile = null;
    void OpenLog(System.IO.FileInfo fileName, System.IO.FileMode mode) {}

    void WriteLog()
    {
        if (!this.logFile.CanWrite)
        {
            throw new System.InvalidOperationException("Logfile cannot be read-only");
        }
        // Else write data to the log and return.
    }
}

- When an argument to a methord causes an exception. In this case, the original exception should be caught and an ArgumentException instance should be created. The original exception should be passed to the constructor of the ArgumentException as the InnerException parameter:

static int GetValueFromArray(int[] array, int index)
{
    try
    {
        return array[index];
    }
    catch (System.IndexOutOfRangeException ex)
    {
        System.ArgumentException argEx = new System.ArgumentException("Index is out of range", "index", ex);
        throw argEx;
    }
}

try and catch blocks

- When exceptions are thrown, you need to be able to handle them. This is done by implementing a try/catch block. Code that could throw an exception is put in the try block and exception handling code goes in the catch block. Below Example shows how to implement a try/catch block. Since an OpenRead() method could throw one of several exceptions, it is placed in the try block. If an exception is thrown, it will be caught in the catch block. The code in  below will print message and stack trace information out to the console if an exception is raised.

using System;
using System.IO;

class tryCatchDemo
{
    static void Main(string[] args)
    {
        try
        {
            File.OpenRead("NonExistentFile");
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

finally block

The purpose of a finally statement is to ensure that the necessary cleanup of objects, usually objects that are holding external resources, happens immediately, even if an exception is thrown. One example of such cleanup is calling Close on a FileStream immediately after use instead of waiting for the object to be garbage collected by the common language runtime, as follows:

static void CodeWithoutCleanup()
{
    System.IO.FileStream file = null;
    System.IO.FileInfo fileInfo = new System.IO.FileInfo("C:\\file.txt");

    file = fileInfo.OpenWrite();
    file.WriteByte(0xF);

    file.Close();
}

To turn the previous code into a try-catch-finally statement, the cleanup code is separated from the working code, as follows.

static void CodeWithCleanup()
{
    System.IO.FileStream file = null;
    System.IO.FileInfo fileInfo = null;

    try
    {
        fileInfo = new System.IO.FileInfo("C:\\file.txt");

        file = fileInfo.OpenWrite();
        file.WriteByte(0xF);
    }
    catch(System.Exception e)
    {
        System.Console.WriteLine(e.Message);
    }
    finally
    {
        if (file != null)
        {
            file.Close();
        }
    }
}

Because an exception can happen at any time within the try block before the OpenWrite() call, or the OpenWrite() call itself could fail, we are not guaranteed that the file is open when we try to close it. The finally block adds a check to make sure the FileStream object is not null before calling the Close method. Without the null check, the finally block could throw its own NullReferenceException, but throwing exceptions in finally blocks should be avoided if possible.


Summary

This has been an introduction to handling exceptions. By now, you should have a good understanding of what an exception is. You can implement algorithms within try/catch blocks that handle exceptions. Additionally, you know how to clean up resources by implementing a finally block whose code is always executed before leaving a method.

Note:
 - Do you like this post, do you want to know more interesting concepts in .net, then subscribe to this blog.
 - You can also mail to dotnetcircle@gmail.com for any queries or issues in .net, we will try to solve and will post in this blog.

Thursday, August 7, 2014

For Learners: How to show User Name in Welcome screen after user login in Asp.net MVC using Linq to Entities

Basic Knowledge in Asp.net MVC to show user name in Welcome screen

Create table with name "tblUsrs" for login users in UserDB in database.

Run below Sql Query in yOur database

Create database UserDB

USE UserDB
CREATE TABLE tblUsers
(
ID  INT PRIMARY KEY IDENTITY(1,1) ON,
USER_NAME VARCHAR(25),
USER_EMAIL VARCHAR(25),
USER_PASSWORD VARCHAR(25)
)

INSERT INTO tblUsers(USER_NAME,USER_EMAIL,USER_PASSWORD)
VALUES("SANJAY","abc@gmail.com","dotnetcircle")

Now, create a controller with name "AccountController" and Change "Index" Action Method to "Login" Action method.


Create a ADO Entity Data Model in Model Folder with name "UserDbEntities" and specify connection settings then Add table " tblUsers";

Add a class "UserModel" in Model class and write the below properties

public string USER_NAME {get;set;}
public string PASSWORD{get;set;}
public string EMAIL{get;set;}
public string Message{get;set;}

Add  View to "Login" action method with strong type model "UserModel " class.

To Design Login Form- write the below html design in your view

@using Html.BeginForm("Login","Account",FormMethod.POST)
{
<table>
<tr>
<td>
@Html.TextBoxFor(m=>m.EMAIL)
</td>
<td>@Html.TextBoxFor(m=>m.PASSWORD)</td>
</tr>
<tr><td><input type="submit" value="Submit" name="btn">
<table>
@Html.DisplayFor(m=>m.Message)
}

and Add another two Action method like below

[HTTPPOST]
public ActionMethod Login(UserModel model,string btn)
{
if(btn=="Submit")
{
 UserDbEntities entites=new UserDbEntities();
var userDetails=entites.tblUser.Where(m=>m.EMAIL==model.EMAIL && m.PASSWORD==model.PASSWORD).FirstOrDefault();

if(userDetails!=null)
{
model.USER_NAME=userDetails.USER_NAME;

//or we can use session like Session["username"]
return RedirecttoAction("Welcome","Account",model);
}
 model.Message="Invalid Username/Password";
}

return View(model);
}
public ActionResult Welcome(UserModel model)
{

return View(model);
}

Add View to Welcome with strong type class "UserModel"

Write the HTML below design

<div>
<h2>Welcome, @Html.DisplayFor(m=>m.USER_NAME")

or @Session["username"]// if we use session
</div>

then run it and type useername and password which in table. That's it.

Do you like this post, then subscribe to this blog for Interesting concepts.
Do you articles on .net , then mail to dotnetcircle@gmail.com to publish in the bog

Wednesday, August 6, 2014

Shortcut keys for Visual studio 2008,2010,2012,2013

Some of useful Coding Shortcut keys  while developing in Visual Studio..


Collapse Items

Ctrl+M+M Collapse / un-collapse current preset area (e.g. method)
Ctrl+M+H Collpase / hide current selection
Ctrl+M+O Collapse declaration bodies
Ctrl+M+A Collapse all
Ctrl+M+X Uncollapse all
Ctrl+m, ctrl+T Collapse Html tag


Edit Code

Ctrl+L Delete current line or selection of lines to and add to clipboard
Ctrl+Shift+L Delete current line or selection of lines
Ctrl+Delete Delete word to right of cursor
Ctrl+Backspace Delete word to left of cursor
Ctrl+Enter Enter blank line above cursor
Ctrl+Shift+Enter Enter blank line below cursor
Ctrl+Shift+U Make uppercase
Ctrl+U Make lowercase (reverse upercase)
Ctrl+K+C Comment selected text
Ctrl+K+U Uncomment selected text
Ctrl+K+\ Remove white space and tabs in selection or around current cursor position
Ctrl+K+D Format document tostyle="width: 10px;" code formatting settings
Ctrl+K+F Format selection to code formatting settings
Ctrl+Shift+Space Display parameter required for selected method
Ctrl+Shift+8 Visualize whitespace (or press Ctrl+r, then Ctrl+w)
Ctrl+K+D Format document to code formatting settings
Ctrl+K+F Format selection to code formatting settings
Ctrl+Shift+T Transpose word to right of cursor; makes b=a out of a=b if cursor was in front of a
Ctrl+T Transpose character left and right of cursor; cursor between ab would make ba
Shift+Alt+T Transpose line: Move line below cursor up and current line down.



IntelliSense and Code Helper

Ctrl+Space Autocomplete word from completion list (or alt+right arrow)
Ctrl+Shift+Space Show parameter info
Ctrl+F12 Display symbol definition
F12 Display symbol declaration
Ctrl+J Open IntelliSense completion list


Build and Debug

F6 Build solution (or Ctrl+shift+b)
Ctrl+Alt+F7 Rebuild solution
Ctrl+Break Cancel build process
Ctrl+\+E Show error list
F9 Toggle breakpoint
Ctrl+B Insert new function breakpoint
F5 Start debugging
F11 Debug / step into
F10 Debug / step over
Shift+F11 Debug / step out
Ctrl+F10 Debug / run to cursor
Ctrl+Alt+Q Show Quickwatch window
Ctrl+Shift+F10 Set current statement to be the next executed
Alt+* (on numeric keyboard) Show nexst statement
Ctrl+Alt+E Show Exception dialog box
Ctrl+F11 Toggle between disassembly and user code view
Shift+F5 Stop Debugging
Ctrl+F5 Bypass debugger
Ctrl+Alt+P Show attach to process window
Ctrl+Alt+break Break all executing threads


Tool Windows

Ctrl+/ Put cursor in the find/command box in toolbar
Ctrl+K+B Open code snippet manager window
Alt+F11 Open macro IDE window
Ctrl+K+W Open bookmark window
Ctrl+Alt+K Open call hierarchy window
Ctrl+Shift+C Open class view window
Ctrl+Alt+A Open Command window
Ctrl+Shift+O Open Output window
Ctrl+Shift+E Open Resource view window
Ctrl+Alt+S Open Server explorer window
Ctrl+Shift+L Open Solution explorer window
Shift+Esc Close Find & Replace Window