Enterprise Application Development
Enterprise Application Development
● S
ecurity:Robust security measures to protect sensitivedata and ensure compliance
with regulations.
● E
nterprise Resource Planning (ERP):Integrates corebusiness processes like
finance, HR, manufacturing, and supply chain management.
● C
ustomer Relationship Management (CRM):Manages acompany's interactions
with current and potential customers.
● S
upply Chain Management (SCM):Oversees the flow ofgoods, information, and
finances from supplier to customer.
● H
uman Resource Management (HRM):Handles employeedata, payroll,
recruitment, and performance management.
● C
ontent Management Systems (CMS):Manages digitalcontent creation and
storage.
● W
aterfall: A linear approach where each phase of developmentmust be completed
before moving on to the next.
● A gile: An iterative and incremental approach that emphasizes flexibility and
customer feedback.
● DevOps: Combines development and operations to improvecollaboration and
productivity through automation and continuous delivery.
P
● rogramming Languages: Java, C#, Python, JavaScript,etc.
● Frameworks: Spring (Java), .NET (C#), Django (Python),Angular/React
(JavaScript).
● Databases: SQL (MySQL, PostgreSQL), NoSQL (MongoDB,Cassandra).
● Cloud Platforms: AWS, Microsoft Azure, Google CloudPlatform.
● Development Tools: Integrated Development Environments(IDEs) like Eclipse,
Visual Studio; version control systems like Git.
M
● onolithic Architecture: A single, unified codebase.
● Service-Oriented Architecture (SOA): Divides functionalityinto services that can be
accessed over a network.
● Microservices Architecture: Breaks down applicationsinto small, loosely coupled
services.
● Event-Driven Architecture: Uses events to triggerand communicate between
services.
● equirement Analysis: Thorough understanding of businessneeds and goals.
R
● Modular Design: Creating reusable and independentmodules.
● Automated Testing: Ensuring software quality throughcontinuous testing.
● Continuous Integration/Continuous Deployment (CI/CD):Automating the
software release process.
Documentation: Maintaining clear and comprehensivedocumentation.
●
7. Challenges
● A
rtificial Intelligence and Machine Learning: Enhancingdecision-making and
automation.
B
● lockchain: Providing secure and transparent transaction processing.
● Internet of Things (IoT): Integrating physical deviceswith enterprise systems.
● Edge Computing: Processing data closer to its sourceto reduce latency.
Conclusion
he .NET Framework is a software development framework developed by Microsoft that
T
provides a runtime environment and a set of libraries and tools for building and running
applications on Windows operating systems. The framework includes a variety of
programming languages, such as C#, F#, and Visual Basic, and supports a range of
application types, including desktop, web, mobile, and gaming applications.
1. T he .NET Framework includes two main components: the Common Language
Runtime (CLR) and the .NET FrameworkClassLibrary.TheCLRisresponsiblefor
managingtheexecutionofcodewritteninanyofthesupportedlanguages,whilethe
classlibraryprovidesalargesetofpre-builtfunctionsandclassesthatcanbeused
to create a wide range of applications.
2. O ne of the key advantages of the .NET Framework is its support for a variety of
programminglanguages.Thismeansthatdeveloperscanchoosethelanguagethat
best fits their needs and expertise, while still being able to use the same set of
libraries and tools provided by the framework.
4. T he .NET Framework also provides a number of features that help improve the
security, reliability, andperformanceofapplications.Theseincludefeaturessuchas
code access security, automatic memory management, and just-in-time (JIT)
compilation, which helps improve the speed of application execution.
5. T he.NETFrameworkisalsodesignedtointegratewithotherMicrosofttechnologies,
suchasMicrosoftSQLServer,MicrosoftSharePoint,andMicrosoftOffice,whichcan
make it easier to build applications that work seamlessly with other Microsoft
products.
verall,the.NETFrameworkisapowerfulandversatiledevelopmentplatformthatprovides
O
a wide range of tools and libraries for building and running applications on Windows
operating systems.
.NETisasoftwareframeworkthatisdesignedanddevelopedbyMicrosoft.Thefirstversion
of the .Net framework was 1.0 which came in the year 2002. In easy words,itisavirtual
machine for compiling and executing programs written in different languages like C#,
VB.Net, etc.
.NETFrameworksupportsmorethan60programminglanguagesofwhich11programming
languages are designed and developed by Microsoft. The remaining Non-Microsoft
Languages are supported by .NET Framework but not designed and developed by Microsoft.
. O
1 LE Technology
2. COM Technology
3. .NET Technology
LE Technology: OLE (Object Linking and Embedding) is one of the technologies of
O
Microsoft’s component document. Basically, its main purpose is to link elements from
different applications with each other.
OMTechnology:ThetechnologyoftheMicrosoftWindowsfamilyoftheoperatingsystem,
C
Microsoft COM (Common Object Model) enables various software components to
communicate.COMismostlyusedbydevelopersforvariouspurposeslikecreatingreusable
oftware components, linking components together to build applications, and also taking
s
advantage of Windows services. The objects ofCOMcanbecreatedwithawiderangeof
programming languages.
.NETTechnology:.NETtechnologyofcollectionorsetoftechnologiestodevelopwindows
andwebapplications.Thetechnologyof.NetisdevelopedbyMicrosoftandwaslaunchedin
Feb. 2002, by basic definition, Microsoft’s new Internet Strategy. It was originally called
NGWS (Next Generation Web Services). It is considered to be one of the most powerful,
popular, and very useful Internet Technology available today.
11 Programming Languages which are designed and developed by Microsoft are:
. C#.NET
1
2. VB.NET
3. C++.NET
4. J#.NET
5. F#.NET
6. JSCRIPT.NET
7. WINDOWS POWERSHELL
8. IRON RUBY
9. IRON PYTHON
10.C OMEGA
11.ASML(Abstract State Machine Language)
ommon Language Runtime(CLR): CLR is the basic and Virtual Machinecomponentof
C
the .NET Framework. It is the run-time environment in the .NET Framework that runs the
code and helps in making the development process easier by providing various services
suchasremoting,threadmanagement,typesafety,memorymanagement,robustness,etc.
Basically, it is responsible for managingtheexecutionof.NETprogramsregardlessofany
.NETprogramminglanguage.Italsohelpsinthemanagementofcode,ascodethattargets
the runtime is known asManagedCode,andcodethatdoesn’ttargetruntimeisknownas
Unmanaged code.
ramework Class Library(FCL): It is the collection of reusable, object-oriented class
F
librariesandmethods,etcthatcanbeintegratedwithCLR.AlsocalledtheAssemblies.Itis
just like the header files in C/C++ and packages in java. Installing the .NET framework
basically is the installation of CLR and FCL into the system. Below is the overviewofthe
.NET Framework.
elease History of .NET Framework and itscompatibilitywiththedifferentWindows
R
version
.Net Framework Architecture
hearchitectureofthe.Netframeworkfocusesontwomainthings:Thefirstoftheseisthat
T
the framework code is largely independent of the language in which it is written. For
example,aframeworkwritteninC#cancontaincallstolibrarieswritteninC++,aswellasto
librarieswritteninotherprogramminglanguages.Thisallows.Netprogramstobeportedto
awidevarietyofplatforms.Thesecondmaingoalofthe.Netframeworkisthatitshouldbe
easy to adopt. This means that the framework should be designed in awaythatmakesit
easy to incorporate new features and new functionality into an existing program. The
framework should also be designed in a way that makes it easy to port the program toa
different platform or make the program run on a different type of computer. The .Net
frameworkhasbeenbuiltinawaythatmakesiteasyforprogrammerstobuildnewfeatures
intotheirprograms.Ithasalsobeenbuiltinawaythatmakesiteasytoextendtheprogram
with new features.
● .NETframework-basedapplicationsthatarewritteninsupportivelanguageslikeC#,
F#, or Visual basic are compiled to Common Intermediate Language (CIL).
● C ompiled code is stored in the form of an assembly file that has a .dll or .exe file
extension.
● When the .NET application runs, Common Language Runtime (CLR) takes the
assembly file and converts the CIL into machine code with the help of the Just In
Time(JIT) compiler.
● Now,thismachinecodecanexecuteonthespecificarchitectureofthecomputeritis
running on.
In .NET, the terms "managed code" and "unmanaged code" refer to how memory
management and other low-level details are handled by the runtime.
Managed Code
anaged code is executed by the Common Language Runtime (CLR) in the .NET
M
framework. The CLR manages memory, handles garbage collection, provides type safety,
and performs other services such as exception handling and security management.
L
● anguages:C#, VB.NET, F#
● Advantages:
○ Automatic memory management (via Garbage Collection)
○ Enhanced security and type safety
○ Cross-language integration and support for other services like reflection
○ Simplified development process, as the runtime handles lower-level
operations
Unmanaged Code
nmanagedcodeisexecuteddirectlybytheoperatingsystem,outsideofthecontrolofthe
U
CLR.Ittypicallyreferstocodewritteninlower-levellanguageslikeCorC++,whichmanage
their own memory and resources.
henyouuseunmanagedcodein.NET,youoftenrelyonplatforminvocation(P/Invoke)
W
to call native functions from Windows DLLs or externallibraries.TheCLRcannotmanage
memory or provide safety guarantees for unmanaged code.
L
● anguages:C, C++, or assembly
● Disadvantages:
○ Manual memory management (using malloc free
, , etc.)
○ More prone to memory leaks and crashes
○ Lack of type safety and security
#include <iostream>
int main()
{
td::cout << "This is unmanaged code running directly on the OS.";
s
return 0;
}
ou can call unmanaged functions from a DLL in managed code using P/Invoke. Here’s an
Y
example:
sing System;
u
using System.Runtime.InteropServices;
lass Program
c
{
// P/Invoke declaration
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();
ven though .NET uses managed code, there are times when you work with unmanaged
E
resources (like file handles, database connections, etc.). In such cases, you must manually
clean up these resources using theIDisposableinterfaceand theusingstatement.
ublic UnmanagedResourceWrapper()
p
{
// Allocate some unmanaged resource
}
UnmanagedResourceWrapper()
~
{
ReleaseUnmanagedResources();
}
}
In .NET, the terms "managed code" and "unmanaged code" refer to how memory
management and other low-level details are handled by the runtime.
Managed Code
L
● anguages:C#, VB.NET, F#
● Advantages:
○ Automatic memory management (via Garbage Collection)
○ Enhanced security and type safety
○ Cross-language integration and support for other services like reflection
○ Simplified development process, as the runtime handles lower-level
operations
Unmanaged Code
hen you use unmanaged code in .NET, you often rely onplatform invocation (P/Invoke)
W
to call native functions from Windows DLLs or external libraries. The CLR cannot manage
memory or provide safety guarantees for unmanaged code.
L
● anguages:C, C++, or assembly
● Disadvantages:
○ Manual memory management (using malloc free
, , etc.)
○ More prone to memory leaks and crashes
○ Lack of type safety and security
int main()
{
std::cout << "This is unmanaged code running directly on the
OS.";
return 0;
}
ou can call unmanaged functions from a DLL in managed code using P/Invoke. Here’s an
Y
example:
sharp
c
Copy code
using System;
using System.Runtime.InteropServices;
class Program
{
// P/Invoke declaration
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling =
true)]
public static extern IntPtr GetForegroundWindow();
ven though .NET uses managed code, there are times when you work with unmanaged
E
resources (like file handles, database connections, etc.). In such cases, you must manually
clean up these resources using theIDisposableinterfaceand theusingstatement.
Example:
ublic class UnmanagedResourceWrapper : IDisposable
p
{
// Assume this represents an unmanaged resource
private IntPtr unmanagedResource;
ublic UnmanagedResourceWrapper()
p
{
// Allocate some unmanaged resource
}
Summary:
M
● anaged code: Code executed by the CLR with automaticmemory management.
● Unmanaged code: Code that runs directly on the OS,typically requiring manual
memory management.
● P/Invoke: Allows managed code to call unmanaged functionsfrom DLLs.
● IDisposable/Finalizer: Used to manage unmanaged resourceswithin managed
code.
Q .NET, "assemblies"
In .NET, "assemblies" are the building blocks of .NET applications. An assembly is a
compiled code library used for deployment, versioning, and security in .NET. Assemblies
containIL (Intermediate Language) codethat the .NETruntime (CLR) executes.
Assemblies also contain metadata that provides details about the types, versioning, culture,
and security information.
Types of Assemblies
ssemblies are typically created during the build process in .NET, whether you're working in
A
Visual Studio or using the .NET CLI. Here's a basic outline of how to create an assembly:
C
● reate a newClass Libraryproject in Visual Studio.
● Add code to the project.
● Build the project to generate a DLL file, which is the compiled assembly.
In .NET, "assemblies" are the building blocks of .NET applications. An assembly is a
compiled code library used for deployment, versioning, and security in .NET. Assemblies
containIL (Intermediate Language) codethat the .NETruntime (CLR) executes.
Assemblies also contain metadata that provides details about the types, versioning, culture,
and security information.
Types of Assemblies
ssemblies are typically created during the build process in .NET, whether you're working in
A
Visual Studio or using the .NET CLI. Here's a basic outline of how to create an assembly:
C
● reate a newClass Libraryproject in Visual Studio.
● Add code to the project.
● Build the project to generate a DLL file, which is the compiled assembly.
sharp
c
Copy code
public class MyLibrary
{
public void PrintMessage()
{
Console.WriteLine("Hello from the assembly!");
}
}
dotnet build
Referencing Assemblies
o use an assembly in another project, you can reference it. Here’s how you can reference a
T
DLL in a .NET project:
R
● ight-click on the project in Solution Explorer.
● SelectAdd > Reference.
● Browse to the DLL you want to reference.
nce referenced, you can use the types and methods defined in the assembly:
O
using MyLibrary;
lass Program
c
{
static void Main()
{
MyLibrary lib = new MyLibrary();
lib.PrintMessage();
}
}
Assembly Versioning
// AssemblyInfo.cs
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
roper versioning is important when you deploy and manage multiple versions of
P
assemblies.
gacutil -i MyLibrary.dll
Strong-Naming Assemblies
sn -k mykey.snk
[assembly: AssemblyKeyFile("mykey.snk")]
1. Build the project. The assembly will now have a strong name.
Summary
basic C# program consists of namespaces, classes, and methods. Here’s the simplest
A
possible C# program:
amespaces: Containers that organize classes and othertypes, preventing name conflicts.
N
Classes: The blueprint for objects in C# (object-orientedprogramming).
Methods: Functions or procedures defined in classesto perform actions. Every C# program
Main()method, which is the entry pointof the application.
must have a
# is a statically typed language, meaning you must declare the type of variables before
C
using them.
Value Types
Example:
int age = 30;
double price = 9.99;
char initial = 'A';
bool isTrue = true;
Reference Types
S
● tring: Stores a sequence of characters.
● Arrays: Stores multiple values of the same type.
● Objects: Represents the base type from which all othertypes derive.
Example:
tring name = "John";
s
int[] numbers = { 1, 2, 3, 4 };
object obj = "Hello, World!";
3. Operators
+,
● Arithmetic operators: -,
*,
/,
%
==
● Comparison operators: !=
, <
, >
, <=
, >=
,
&&
● Logical operators: ||
, !
,
=
● Assignment operators: +=
, -=
, *=
, /=
,
++
● Increment/Decrement operators: --
,
int a = 5;
int b = 10;
int sum = a + b; // Addition
bool isEqual = (a == b); // Comparison
ontrol flow statements are used to make decisions and execute code conditionally or
C
repeatedly.
Conditional Statements
●
if
: Executes a block of code if a condition is true.
●
else
: Executes if the condition is false.
●
else if
: Used for multiple conditions.
●
switch
: A more efficient way to handle multiple possiblevalues for a variable.
Example:
int x = 10;
witch (x)
s
{
case 1:
Console.WriteLine("x is 1");
break;
case 10:
Console.WriteLine("x is 10");
break;
default:
Console.WriteLine("x is something else");
break;
}
Loops
●
for
: Loops through a block of code a specified numberof times.
●
while
: Repeats a block of code while a condition istrue.
●
do-while while
: Same as , but it checks the conditionafter the first iteration.
●
foreach
: Loops through items in a collection (arrays,lists, etc.).
Example:
// for loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
ethods in C# are blocks of code that perform a task. Methods can have parameters and
M
return values.
Example:
lass Program
c
{
static void Main()
{
int result = Add(5, 3); // Call the method
Console.WriteLine(result);
}
# is an object-oriented language, and classes are its core building blocks. Classes define
C
the properties and behavior of objects.
Example:
lass Car
c
{
public string Make { get; set; }
public string Model { get; set; }
lass Program
c
{
static void Main()
{
Car myCar = new Car();
myCar.Make = "Toyota";
myCar.Model = "Camry";
myCar.Start();
}
}
● E ncapsulation: Bundling of data (fields) and methodsthat operate on the data into a
single unit (class).
● Abstraction: Hiding complex implementation detailsand exposing only the essential
features.
● Inheritance: Allows one class to inherit members (fields,methods) from another
class.
● Polymorphism: Allows one interface to be used fora general class of actions (e.g.,
method overriding, interfaces).
Example of Inheritance:
lass Animal
c
{
public void Eat()
{
Console.WriteLine("Eating");
}
}
lass Program
c
{
static void Main()
{
og dog = new Dog();
D
dog.Eat(); // Inherited method
dog.Bark(); // Dog-specific method
}
}
try
C# provides structured exception handling using catch
, finallyblocks.
, and
Example:
try
{
int result = 10 / 0; // This will cause an exception
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
Console.WriteLine("This code runs no matter what.");
}
9. Properties
roperties in C# provide a flexible mechanism to read, write, or compute the values of
P
private fields.
Example:
lass Person
c
{
private string name;
10. Interfaces
Interfaces define a contract for classes, specifying what methods or properties they must
implement. Unlike inheritance, interfaces only define methods without implementation.
Example:
interface IAnimal
{
void MakeSound();
}
Summary:
C
● # is object-oriented: It revolves around classesand objects.
● Data types: Strongly typed language with both valuetypes and reference types.
● Control flow: Uses conditional statements (if switch
, )and loops (
for while
, ,
oreach
f ).
● OOP principles: Inheritance, encapsulation, polymorphism,and abstraction.
Methods and properties: Central to defining behaviorand controlling access to
●
data.
try
● Exception handling: Structured with catch
, finally
, and .
1. Boxing
Example of Boxing:
int num = 123; // num is a value type
object obj = num; // Boxing: num is stored as an object
2. Unboxing
nboxingis the reverse process of boxing, where anobject (which holds a value type) is
U
explicitly cast back to its original value type. Unboxing requires explicit casting, and if you
attempt to unbox an object to the wrong value type, a InvalidCastExceptionwill be
thrown.
Example of Unboxing:
bject obj = 123;
o // Boxing
int num = (int)obj; // Unboxing: obj is cast back to an int
Key Points
● B oxing: Conversion of a value type to a referencetype (object). The value is copied
from the stack to the heap.
● Unboxing: Conversion of a reference type (object)back to a value type. The object
is cast back to its original value type, and the value is copied from the heap to the
stack.
● Performance considerations: Boxing and unboxing involveoverhead because they
involve copying data between the stack and heap and allocating memory on the
heap. Excessive boxing and unboxing operations can impact performance, so it's
generally a good practice to avoid them when possible.
lass Program
c
{
static void Main()
{
int value = 42; // Value type
object obj = value; // Boxing: value is stored in obj as an object
Console.WriteLine(obj); // Output: 42
Performance Impact
hile boxing and unboxing are useful, they can lead to performance issues if used
W
excessively due to:
1. H eap allocation: Boxing creates objects on the heap,which incurs memory
allocation overhead.
2. Garbage collection: The boxed objects will eventuallybe garbage collected, adding
further overhead.
3. Type safety: Unboxing requires type casting, and incorrectcasting can lead to
runtime exceptions.
Alternatives to Boxing/Unboxing
o avoid boxing and unboxing, you can usegenerics.Generics allow you to create classes,
T
methods, and structures that work with any data type without requiring boxing and unboxing.
Summary
Q Introduction to ADO.Net
DO.NET(ActiveX Data Objects .NET) is a set of classes that expose data access services
A
for .NET applications. It is a part of the .NET Framework and provides a bridge between a
database and a .NET application, allowing you to work with data in a structured and
disconnected way.
ADO.NET Architecture
● C onnected Architecture: You keep an active connectionto the database while
DataReaderfor real-time reading of
working with the data. For example, using
database records.
● Disconnected Architecture: Data is retrieved and workedon independently of the
database connection.DataSetand
DataAdapterare keycomponents for
disconnected data access.
hile (reader.Read())
w
{
Console.WriteLine(reader["FirstName"] + " " + reader["LastName"]);
}
r eader.Close();
connection.Close();
}
SqlCommandwith an
To insert data into the database, you can use the INSERTstatement.
onnection.Open();
c
command.ExecuteNonQuery();
connection.Close();
}
UPDATEstatementwith a
To update existing records, use the SqlCommand
.
tring query = "UPDATE Employees SET Age = @Age WHERE FirstName = @FirstName
s
AND LastName = @LastName";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Age", 35);
command.Parameters.AddWithValue("@FirstName", "John");
command.Parameters.AddWithValue("@LastName", "Doe");
onnection.Open();
c
command.ExecuteNonQuery();
connection.Close();
}
DELETEstatement.
To delete data from the database, use a
onnection.Open();
c
command.ExecuteNonQuery();
connection.Close();
}
Advantages of ADO.NET
● S calability: The disconnected model allows ADO.NETto work with data in a
scalable way, as it doesn’t need to keep the connection open.
● Flexibility: ADO.NET supports various types of datasources, including relational
databases, XML, and web services.
● Performance: ADO.NET’s DataReaderoffers fast, efficientaccess to data.
Summary
DO.NET is widely used in enterprise applications where reliable, scalable, and efficient
A
data access is required.
Q SQL injection
QL injectionis a type of security vulnerability that allows an attacker to interfere with the
S
queries an application makes to its database. This occurs when user input is improperly
handled, enabling malicious SQL code to be executed. SQL injection can result in
unauthorized access to sensitive data, database modification, or even complete system
compromise.
QL injection happens when an application inserts untrusted data (such as form inputs) into
S
an SQL query without proper validation or escaping. Attackers can inject malicious SQL
code into the input fields, which is then executed by the database.
tring query = "SELECT * FROM Users WHERE Username = '" + username + "' AND
s
Password = '" + password + "'";
●
username=
' OR 1=1 --
●
password=
anything
SELECT * FROM Users WHERE Username = '' OR 1=1 --' AND Password = 'anything'
he
T OR 1=1condition is always true, and the
--isa comment marker that ignores the rest
of the query. This means the attacker can bypass authentication and log in without knowing
the actual credentials.
1. C lassic SQL Injection: This is when user inputs areinjected into SQL queries
directly without validation, resulting in unintended execution of commands.
2. Blind SQL Injection: In blind SQL injection, attackersdon't get direct feedback from
the database. They send queries and infer information by analyzing the application's
behavior (such as response time or error messages).
3. Error-based SQL Injection: This occurs when the attackermanipulates inputs to
cause the database to throw errors. The error messages can reveal sensitive
information about the database's structure or contents.
4. Union-based SQL Injection: In this form, attackersuse the UNIONoperator to
combine the results of multiple queries into a single response, potentially extracting
data from other tables.
5. T
ime-based SQL Injection: Attackers use time delays in queries to infer whether the
input is being executed, even when no data is returned. For example, injecting a
SLEEP(5)function into the query to cause a delayand observe the response.
1. U
se Parameterized Queries (Prepared Statements)Themost effective way to
prevent SQL injection is to use parameterized queries or prepared statements. This
ensures that user input is treated as data, not executable code.
Example of Parameterized Query in C#:
tring query = "SELECT * FROM Users WHERE Username = @Username AND Password =
s
@Password";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Username", username);
command.Parameters.AddWithValue("@Password", password);
command.ExecuteNonQuery();
}
@Usernameand
In this example, the user input is bound to the @Passwordparameters,
preventing SQL injection.
Use Stored ProceduresStored procedures can also helpprevent SQL injection by
encapsulating SQL queries and ensuring input validation.
Example of Stored Procedure:
1. L east Privilege PrincipleEnsure that the databaseuser account used by the
application has the least privileges required. For example, avoid using admin
accounts for queries.
2. Avoid Dynamic SQLAvoid constructing SQL queries dynamicallyusing string
concatenation. Always use parameterized queries instead.
3. Escape User Input (as a last resort)If dynamic SQLis absolutely necessary,
ensure proper escaping of user input to prevent malicious characters from being
executed.
4. Use ORM FrameworksUse Object-Relational Mapping (ORM)frameworks like
Entity Framework, which abstract SQL queries and prevent SQL injection by using
safe methods for querying.
onnection.Open();
c
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
Console.WriteLine("Login successful!");
}
else
{
Console.WriteLine("Login failed.");
}
reader.Close();
}
}
.
1 se parameterized queries(prepared statements).
U
2. Validate and sanitize all user inputs.
3. Use stored proceduresfor database queries.
4. Avoid dynamic SQLwhere possible.
5. Limit database privilegesfor the application account.
6. Use ORM frameworksto abstract SQL queries.
y following these best practices, you can effectively reduce the risk of SQL injection in your
B
application.
Q Parameterized queries
1. S ecurity: They prevent SQL injection by ensuring thatuser input is treated as data
rather than part of the SQL command.
2. Performance: The SQL query execution plan can be reused,which can improve
performance for repeated queries.
3. Readability: Parameterized queries often make codecleaner and easier to
understand.
In a parameterized query, placeholders are used for the parameters, and the actual values
are supplied separately. The database engine handles the values as data rather than
executable SQL, which prevents malicious input from being executed as code.
his code concatenates the user input directly into the SQL query, making it vulnerable to
T
SQL injection.
tring query = "SELECT * FROM Users WHERE Username = '" + username + "' AND
s
Password = '" + password + "'";
qlCommand command = new SqlCommand(query, connection);
S
command.ExecuteNonQuery();
onnection.Open();
c
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
Console.WriteLine("Login successful!");
}
else
{
Console.WriteLine("Login failed.");
}
reader.Close();
}
Key Points:
If you're using stored procedures, you can also pass parameters in a secure way.
1. E xecution Plan Reuse: When you use parameterized queries,the database can
reuse the execution plan, improving performance for repeated queries with different
parameters.
2. Reduced Parsing: The database doesn't need to parseand compile the SQL query
for every execution since the structure of the query remains the same.
SqlParameterclass
You can specify different data types for the parameters by using the
AddWithValue(which infers the data typeautomatically).
instead of
tring query = "INSERT INTO Employees (FirstName, Age) VALUES (@FirstName, @Age)";
s
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar) {
Value = "John" });
command.Parameters.Add(new SqlParameter("@Age", SqlDbType.Int) { Value = 30 });
onnection.Open();
c
command.ExecuteNonQuery();
}
SqlParameterOver
Benefits of Using AddWithValue
● T
he@Categoryand@Priceparameters are safely passed,avoiding SQL injection
attacks and making the query more efficient.
Summary
y using parameterized queries, you can ensure that your database interactions are both
B
secure and efficient.
Q Usage of Dataset
In ADO.NET, aDataSetis an in-memory representationof data that can hold multiple tables
and their relationships. It allows you to work with data in a disconnected manner, meaning
you can retrieve data from a database, manipulate it locally, and then, if needed, update the
database without maintaining a persistent connection.
D
● isconnected Architecture: Data is retrieved and workedwith offline.
● Multiple Tables: A DataSetcan contain multiple
DataTableobjects.
● Data Relationships: You can define relationships betweentables (similar to foreign
keys).
● In-Memory Cache: Data is stored in memory, and changescan be made before
syncing with the database.
● XML Support: DataSetcan be serialized to XML anddeserialized from XML,
making it suitable for data exchange.
DataSet
To create and fill a DataAdaptertoretrieve data from a database.
, use a
// Define the SQL query
string query = "SELECT * FROM Employees";
DataSet
● Update: You can modify existing rows in the .
NewRowand
● Insert: You can add new rows using Add
.
Deletemethod.
● Delete: You can delete rows using the
Updatemethod of the
The SqlDataAdapterwill applyany changes (inserts, updates,
DataSetto the database.
deletes) from the
DataTableobjectsin a
ou can define relationships between
Y DataSetsimilar to foreign
key constraints in a database.
dataSet.WriteXml("employees.xml");
Advantages of DataSet
1. D isconnected Data Access: A DataSetallows you towork with data without
needing a continuous connection to the database.
2. In-Memory Data: It can store data in memory, and thedata can be modified, filtered,
and sorted before committing changes to the database.
3. Multiple Tables and Relationships: You can managemultiple tables in one
DataSet
, defining relationships between them justlike in a relational database.
4. X DataSetsupports reading and writingXML, making it easy to
ML Integration:
exchange data with other systems or store data locally.
// Fill the DataSet with data from the Employees table
adapter.Fill(dataSet, "Employees");
Summary
● D ataSetis an in-memory representation of data thatcan handle multiple tables and
relationships in a disconnected mode.
● It allows you to retrieve, manipulate, and update data without keeping an open
connection to the database.
DataSetusing a
● You can fill a DataAdapter , and changesmade to the data can
Updatemethod.
e sent back to the database using the
b
It supports XML integration, making it useful for data exchange and persistence.
●
1. DataAdapter
DataSetor
DataAdapterserves as a bridge between the databaseand the
A DataTable
.
It is responsible for:
DataSetor
● Retrieving datafrom the database into a DataTable
.
● S
ending updatesfrom the DataSetor
DataTablebackto the database (for
inserts, updates, and deletes).
It consists of four important SQL commands (though not all are mandatory):
● electCommand: Retrieves data from the database.
S
● InsertCommand: Inserts new rows into the database.
● UpdateCommand: Updates existing rows in the database.
● DeleteCommand: Deletes rows from the database.
● D DataSetor
isconnected Operation: Once the data is fetched intoa DataTable ,
the connection can be closed, and changes are made locally in memory.
● Batch Processing: You can batch multiple changes (inserts,updates, deletes) and
then push them to the database in one go.
● Custom Commands: You can manually define SQL commandsfor updating data or
CommandBuilderto automatically generatethem.
rely on a
// Now the DataSet contains a DataTable named "Employees" with the retrieved data
DataTable employeesTable = dataSet.Tables["Employees"];
// Sending changes back to the database would require UpdateCommand (handled by
CommandBuilder)
}
2. CommandBuilder
SELECTquery, the
● Automatic Command Generation: If you have a basic
ommandBuildercan generate the
C INSERT UPDATE
, DELETESQL
, and
statements automatically.
CommandBuilderworks witha
Use with DataAdapter: The
● DataAdapterto
DataSetor
handle changes made to the DataTable
.
CommandBuilderrequiresthat the
● Table Schema Required: The
SelectCommandreturns enough schema information (e.g.,primary key) to correctly
INSERT
generate the UPDATE
, DELETEcommands.
, and
// Update the database with the changes made in the DataSet
adapter.Update(dataSet, "Employees");
}
DataSet
● DataAdapterretrieves the data into a .
DataSet
● Changes (like inserting a new row) are made in memory in the .
INSERT
● TheCommandBuilderautomatically generates the necessary UPDATE
, ,
DELETESQL commands.
and
Updatemethod of the
● The DataAdaptersends the changesback to the database.
Step-by-Step Process
SelectCommandof the
1. Fill the DataSet: The DataAdapterfetches data from the
atabase and populates the
d DataSetor
DataTable .
2. Manipulate Data: You can insert, update, or deleterows in the
DataSet
/
D
ataTablein memory.
3. C CommandBuildergeneratesthe necessary SQL
ommandBuilder Setup: The
commands (INSERT, UPDATE, DELETE) based on the schema of the data in the
DataSet
.
Updatemethod of the
4. Update the Database: The DataAdapterpushes the
DataSetback to the database, usingthe commands generated by
changes from the
CommandBuilder
the .
Limitations of CommandBuilder
Summary
hese components are essential for building data-driven applications that need to handle
T
large datasets or operate in environments with intermittent connectivity.
Q Introduction to delegate
delegatein C# is a type that defines a method signatureand can reference a method that
A
matches this signature. In simpler terms, delegates are objects that hold references to
methods. They are often used to implement event handling and callback mechanisms.
elegates enable methods to be passed as parameters, making them highly useful for
D
designing flexible and extensible code.
Key Features of Delegates:
1. T ype-Safe: Delegates are type-safe, meaning the signature(return type and
parameters) of the method the delegate points to must match the delegate's
definition.
2. Encapsulation of Methods: Delegates encapsulate methods,allowing them to be
passed around like objects.
3. Multicast: A delegate can reference multiple methods,which is known as a multicast
delegate.
4. Used for Callbacks: Delegates are commonly used forcallbacks and event handling
in C#.
A delegate is declared with a specific method signature (return type and parameter types).
You can assign a method to a delegate if the method matches the delegate's signature.
// Invoking the delegate (calling the method via the delegate)
del("Hello, this is a delegate example.");
}
}
nce a method is assigned to a delegate, you can invoke the delegate just like you would
O
call the method itself:
Types of Delegates
. S
1 ingle-cast Delegate: A delegate that holds a referenceto a single method.
2. Multi-cast Delegate: A delegate that holds referencesto multiple methods. When
invoked, all the methods are called in order.
Method1and
Here, both Method2are invoked when thedelegate
delis called.
● A ction: Represents a method that takes zero or moreinput parameters and returns
void
.
● Func: Represents a method that takes zero or moreinput parameters and returns a
value.
bool
● Predicate: Represents a method that takes a singleparameter and returns a
value.
Funcdelegate is used when a method returns avalue. The last type parameter of the
The
Funcdelegate represents the return type.
elegates can be used to implement callbacks, where one method calls another method
D
asynchronously and notifies the caller when the operation is completed.
● A delegate Notifyis declared, which represents amethod with no parameters and
no return type.
● An event ProcessCompletedis based on the delegate Notify .
StartProcessmethod simulates a process and thenraises the
● The
ProcessCompletedevent.
● T
heProcessCompletedHandleris the method that getscalled when the event is
raised.
Summary
A
● delegateis a reference type that encapsulates amethod.
● Delegates are useful for designing flexible applications with callbacks, events, and
dynamic method invocation.
● Single-cast delegatesrefer to a single method, whilemulti-cast delegatescan
invoke multiple methods.
● C# provides built-in delegates likeAction,Func,andPredicateto simplify common
delegate use cases.
● Delegates are heavily used in event-driven programming and callback patterns in C#.
Q Multicast Delegates