string x = "AABBCDEFF";
string result = "";
foreach (char value in x)
{
if (result.IndexOf(value) == -1)
{
result += value;
}
}
x= result;
SQL EXAMPLES
Query to Verify Duplicates Exist in Department table...
SELECT DepartmentName, COUNT(*)
FROM Department
GROUP BY DepartmentName
HAVING COUNT(*) > 1
Find the second largest data from the Categories table...
select max(CategoryId) from Categories where CategoryId < (select max(CategoryId) from Categories)
select max(FeeTotalAmount) from Fees where FeeTotalAmount not in (select max(FeeTotalAmount) from Fees)
Get the top 5 data from Categories table...
select * from Categories where CategoryId in (select distinct top 5 CategoryId from Categories order by CategoryId desc)
Without using keyword TOP :- select * from Categories order by CategoryId desc offset 0 rows fetch first 5 rows only
Update a table by converting all 'Male' to 'Female'...
update Users
set Gender = case
when Gender = 'Male' then 'Female'
else 'Female'
end
SELECT DepartmentName, COUNT(*)
FROM Department
GROUP BY DepartmentName
HAVING COUNT(*) > 1
Find the second largest data from the Categories table...
select max(CategoryId) from Categories where CategoryId < (select max(CategoryId) from Categories)
select max(FeeTotalAmount) from Fees where FeeTotalAmount not in (select max(FeeTotalAmount) from Fees)
Get the top 5 data from Categories table...
select * from Categories where CategoryId in (select distinct top 5 CategoryId from Categories order by CategoryId desc)
Without using keyword TOP :- select * from Categories order by CategoryId desc offset 0 rows fetch first 5 rows only
Update a table by converting all 'Male' to 'Female'...
update Users
set Gender = case
when Gender = 'Male' then 'Female'
else 'Female'
end
ASP.NET Web API
The ASP.NET Web API is an ideal platform for building Restful applications on the .NET Framework.
Definition
Web API is an Application Programming Interface (API) that is used to enable the communication or interaction with software components with each other. ASP.NET Web API is a framework that makes it easy to build HTTP Service that reaches a broad range of clients, including browsers and mobile devices. Using ASP.NET, web API can enable communicating by different devices from same database.
Uses of Web API
It is used to access service data in web applications as well as many mobile apps and other external devices.
It is used to create RESTful web services. REST stands for Representational State Transfer, which is an architectural style for networked hypermedia applications.
It is primarily used to build Web Services that are lightweight, maintainable, and scalable, and support limited bandwidth.
It is used to create simple HTTP Web Service. It supports XML, JSON, and other data formats.
Definition
Web API is an Application Programming Interface (API) that is used to enable the communication or interaction with software components with each other. ASP.NET Web API is a framework that makes it easy to build HTTP Service that reaches a broad range of clients, including browsers and mobile devices. Using ASP.NET, web API can enable communicating by different devices from same database.
Uses of Web API
It is used to access service data in web applications as well as many mobile apps and other external devices.
It is used to create RESTful web services. REST stands for Representational State Transfer, which is an architectural style for networked hypermedia applications.
It is primarily used to build Web Services that are lightweight, maintainable, and scalable, and support limited bandwidth.
It is used to create simple HTTP Web Service. It supports XML, JSON, and other data formats.
Use of AuthConfig, BundleConfig, FilterConfig , RouteConfig and WebApiConfig in App_Start() folder in MVC
BundleConfig.cs -
This is used to create and register bundles for CS and JS files.By default various bundles are added in this file including jQuery,jQueryUI,jQuery validation,Modernizer and Site Css..
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
//Adding StyleBundle to BundleCollection
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.min.css",
"~/Content/mystyle.min.css"));
//Adding ScriptBundle to BundleCollection
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery-1.7.1.min.js",
"~/Scripts/jquery.validate.min.js"));
}
}
AuthConfig.cs -
Used to register external authentication providers for eg. if you want to enable users to log in with
credentials from an external provider, such as Facebook, Twitter, Microsoft, or Google, and then integrate some of the functionality from those providers into your web application.
RouteConfig.cs -
This is used to register various route patterns for your Asp.Net MVC application. By default,one route is registered here named as Default Route.
WebApiConfig.cs -
This is used to register various WEB API routes like as Asp.Net MVC,as well as set any additional WEB API configurations settings.
FilterConfig.cs -
This is used to create and register global MVC filter error filter,action filter etc.By default it contains
HandleErrorAttribute filter.
This is used to create and register global MVC filter:
for eg:-
1. Authentication filters (Executed First)
2. Authorization filters
3. Action filters
4. Result filters
5. Exception filters (Exected Last)
Configuring Filters -
You can configure your own custom filter into your application at following three levels:
1. Global level
By registering your filter into Application_Start event of Global.asax.cs file:
protected void Application_Start()
{
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
2. Controller level
By putting your filter on the top of the controller name:
[Authorize(Roles="Admin")]
public class AdminController : Controller
{
// Logic goes here
}
3. Action level
By putting your filter on the top of the action name:
public class UserController : Controller
{
[Authorize(Users="User1,User2")]
public ActionResult LinkLogin(string provider)
{
// Logic goes here
return View();
}
}
This is used to create and register bundles for CS and JS files.By default various bundles are added in this file including jQuery,jQueryUI,jQuery validation,Modernizer and Site Css..
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
//Adding StyleBundle to BundleCollection
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.min.css",
"~/Content/mystyle.min.css"));
//Adding ScriptBundle to BundleCollection
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery-1.7.1.min.js",
"~/Scripts/jquery.validate.min.js"));
}
}
AuthConfig.cs -
Used to register external authentication providers for eg. if you want to enable users to log in with
credentials from an external provider, such as Facebook, Twitter, Microsoft, or Google, and then integrate some of the functionality from those providers into your web application.
RouteConfig.cs -
This is used to register various route patterns for your Asp.Net MVC application. By default,one route is registered here named as Default Route.
WebApiConfig.cs -
This is used to register various WEB API routes like as Asp.Net MVC,as well as set any additional WEB API configurations settings.
FilterConfig.cs -
This is used to create and register global MVC filter error filter,action filter etc.By default it contains
HandleErrorAttribute filter.
This is used to create and register global MVC filter:
for eg:-
1. Authentication filters (Executed First)
2. Authorization filters
3. Action filters
4. Result filters
5. Exception filters (Exected Last)
Configuring Filters -
You can configure your own custom filter into your application at following three levels:
1. Global level
By registering your filter into Application_Start event of Global.asax.cs file:
protected void Application_Start()
{
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
2. Controller level
By putting your filter on the top of the controller name:
[Authorize(Roles="Admin")]
public class AdminController : Controller
{
// Logic goes here
}
3. Action level
By putting your filter on the top of the action name:
public class UserController : Controller
{
[Authorize(Users="User1,User2")]
public ActionResult LinkLogin(string provider)
{
// Logic goes here
return View();
}
}
Difference Between String and Stringbuilder in C#
String
String is immutable, Immutable means if you create string object then you cannot modify it and It always create new object of string type in memory.
Example :-
string strMyValue = "Hello Visitor";
// create a new string instance instead of changing the old one
strMyValue += "How Are";
strMyValue += "You ??";
Stringbuilder
StringBuilder is mutable, means if create string builder object then you can perform any operation like insert, replace or append without creating new instance for every time.it will update string at one place in memory doesn't create new space in memory.
Example :-
StringBuilder sbMyValue = new StringBuilder("");
sbMyValue.Append("Hello Visitor");
sbMyValue.Append("How Are You ??");
string strMyValue = sbMyValue.ToString();
String is immutable, Immutable means if you create string object then you cannot modify it and It always create new object of string type in memory.
Example :-
string strMyValue = "Hello Visitor";
// create a new string instance instead of changing the old one
strMyValue += "How Are";
strMyValue += "You ??";
Stringbuilder
StringBuilder is mutable, means if create string builder object then you can perform any operation like insert, replace or append without creating new instance for every time.it will update string at one place in memory doesn't create new space in memory.
Example :-
StringBuilder sbMyValue = new StringBuilder("");
sbMyValue.Append("Hello Visitor");
sbMyValue.Append("How Are You ??");
string strMyValue = sbMyValue.ToString();
What is AJAX ?
AJAX stands for Asynchronous JavaScript and XML. This is a cross platform technology which speeds up response time. The AJAX server controls add script to the page which is executed and processed by the browser.
However like other ASP.NET server controls, these AJAX server controls also can have methods and event handlers associated with them, which are processed on the server side.
The control toolbox in the Visual Studio IDE contains a group of controls called the 'AJAX Extensions'
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.
The ScriptManager Control
The ScriptManager control is the most important control and must be present on the page for other controls to work.
It has the basic syntax:
ID="ScriptManager1" runat="server";
If you create an 'Ajax Enabled site' or add an 'AJAX Web Form' from the 'Add Item' dialog box, the web form automatically contains the script manager control. The ScriptManager control takes care of the client-side script for all the server side controls.
The UpdatePanel Control : The UpdatePanel control is a container control and derives from the Control class. It acts as a container for the child controls within it and does not have its own interface.
For example, if a button control is inside the update panel and it is clicked, only the controls within the update panel will be affected, the controls on the other parts of the page will not be affected.
The UpdateProgress Control
The UpdateProgress control provides a sort of feedback on the browser while one or more update panel controls are being updated. It provides a visual acknowledgement like "Loading page...", indicating the work is in progress.
The Timer Control
The timer control is used to initiate the post back automatically. This could be done in two ways :
(1) Setting the Triggers property of the UpdatePanel control:
(2) Placing a timer control directly inside the UpdatePanel to act as a child control trigger. A single timer can be the trigger for multiple UpdatePanels.
However like other ASP.NET server controls, these AJAX server controls also can have methods and event handlers associated with them, which are processed on the server side.
The control toolbox in the Visual Studio IDE contains a group of controls called the 'AJAX Extensions'
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.
The ScriptManager Control
The ScriptManager control is the most important control and must be present on the page for other controls to work.
It has the basic syntax:
ID="ScriptManager1" runat="server";
If you create an 'Ajax Enabled site' or add an 'AJAX Web Form' from the 'Add Item' dialog box, the web form automatically contains the script manager control. The ScriptManager control takes care of the client-side script for all the server side controls.
The UpdatePanel Control : The UpdatePanel control is a container control and derives from the Control class. It acts as a container for the child controls within it and does not have its own interface.
For example, if a button control is inside the update panel and it is clicked, only the controls within the update panel will be affected, the controls on the other parts of the page will not be affected.
The UpdateProgress Control
The UpdateProgress control provides a sort of feedback on the browser while one or more update panel controls are being updated. It provides a visual acknowledgement like "Loading page...", indicating the work is in progress.
The Timer Control
The timer control is used to initiate the post back automatically. This could be done in two ways :
(1) Setting the Triggers property of the UpdatePanel control:
(2) Placing a timer control directly inside the UpdatePanel to act as a child control trigger. A single timer can be the trigger for multiple UpdatePanels.
Dependency Injection in C#
Dependency Injection (DI) is a software design pattern that allows us to develop loosely coupled code. When designing an object oriented application, a major concern of design is "Design must be loosely coupled". Loose coupling offers us greater re-usability, maintainability and test-ability.
There are three basic type of Dependency Injection
Construction Injection
Setter Injection
Interface based Injection.
Constructor Injection
The basic idea of constructor-injection is that the object has no defaults or single constructor; instead specified values are required at the time of creation to instantiate the object. In other words Constructor injection uses parameters to inject dependencies.
Setter Injection
Setter Injection does not require the constructor to be change but dependencies are passed through public properties that are exposed. Setter Injection allows us costly resources or services to be created as late as possible and only when required.
Interface Based Injection
Interface based Injection is implemented using common interfaces that other classes need to implement to inject dependencies. This type of injected from both the way either constructor injection or setter injection.
There are three basic type of Dependency Injection
Construction Injection
Setter Injection
Interface based Injection.
Constructor Injection
The basic idea of constructor-injection is that the object has no defaults or single constructor; instead specified values are required at the time of creation to instantiate the object. In other words Constructor injection uses parameters to inject dependencies.
Setter Injection
Setter Injection does not require the constructor to be change but dependencies are passed through public properties that are exposed. Setter Injection allows us costly resources or services to be created as late as possible and only when required.
Interface Based Injection
Interface based Injection is implemented using common interfaces that other classes need to implement to inject dependencies. This type of injected from both the way either constructor injection or setter injection.
What is the difference between the stack and the heap?
Stack and Heap are the two sections of the memory layout of a process.
The stack is used to keep track of variables/parameters local to a function in a program.
Whenever you call a new function, a new stack frame is pushed to the stack with parameters and variables local to that function. When that function returns, the stack frame is popped out and the context switches back to the previous function
A heap is a kind of a global memory pool. A function can allocate memory on the heap if it wants the data to live longer than the function itself. Objects allocated on the heap are accessible to all the functions, given they have the reference/address of the object to access it.
The stack is used to keep track of variables/parameters local to a function in a program.
Whenever you call a new function, a new stack frame is pushed to the stack with parameters and variables local to that function. When that function returns, the stack frame is popped out and the context switches back to the previous function
A heap is a kind of a global memory pool. A function can allocate memory on the heap if it wants the data to live longer than the function itself. Objects allocated on the heap are accessible to all the functions, given they have the reference/address of the object to access it.
View State Vs. Session State Vs. Application State
View State
View State is a technique to maintain the state of controls during page post-back, meaning it stores the page value at the time of post-back (sending and receiving information from the server) of your page and the view state data can be used when the page is posted back to the server and a new instance of the page is created.
View state data is nothing but a serialized base-64 encoded string stored in a hidden input field on the page and it travels between the browser and the server on every user request and response.
View State advantages:
Very easy to implement.
Stored on the client browser in a hidden field as a form of Base64 Encoding String not encrypted and can be decoded easily.
Good with HTTP data transfer
View State disadvantages:
The performance overhead for the page is larger data stored in the view state.
Stored as encoded and not very safe to use with sensitive information.
Where to Use : View state should be used when the user needs to store a small amount of data at the client browser with faster retrieval. The developer should not use this technique to retain state with larger data since it will create a performance overhead for the webpage. It should be used for sending data from one page to another.
ASP.NET Session State
Session State is another state management technique to store state, meaning it helps in storing and using values from previous requests. Whenever the user requests a web form from a web application it will get treated as a new request. an ASP.NET session will be used to store the previous requests for a specified time period.
By default, an ASP.NET session state is enabled for all ASP.NET applications. Session state data is shared across all the web pages.
Session variables are single-user global data stored on the web server, meaning by default a session state variable is stored in the web server memory and is available across all pages but it will be for a single session.
Application State
Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions.
Application state variables are also used to store data when navigating from one page to another. It's multi-user Global data meaning it will be accessible across all pages and all sessions.
An application state variable does not have any default time unlike session variables. It will end when the application hosting process is restarted or the application ends.
What is the difference between SessionState and ViewState?
Session state is saved on the server, ViewState is saved in the page.
Session state is usually cleared after a period of inactivity from the user (no request happened containing the session id in the request cookies).
The view state is posted on subsequent post back in a hidden field.
SessionState
Can be persisted in memory, which makes it a fast solution. Which means state cannot be shared in the Web Farm/Web Garden.
Can be persisted in a Database, useful for Web Farms / Web Gardens.
Is Cleared when the session dies - usually after 20min of inactivity.
ViewState
Is sent back and forth between the server and client, taking up bandwidth.
Has no expiration date.
Is useful in a Web Farm / Web Garden
View State is a technique to maintain the state of controls during page post-back, meaning it stores the page value at the time of post-back (sending and receiving information from the server) of your page and the view state data can be used when the page is posted back to the server and a new instance of the page is created.
View state data is nothing but a serialized base-64 encoded string stored in a hidden input field on the page and it travels between the browser and the server on every user request and response.
View State advantages:
Very easy to implement.
Stored on the client browser in a hidden field as a form of Base64 Encoding String not encrypted and can be decoded easily.
Good with HTTP data transfer
View State disadvantages:
The performance overhead for the page is larger data stored in the view state.
Stored as encoded and not very safe to use with sensitive information.
Where to Use : View state should be used when the user needs to store a small amount of data at the client browser with faster retrieval. The developer should not use this technique to retain state with larger data since it will create a performance overhead for the webpage. It should be used for sending data from one page to another.
ASP.NET Session State
Session State is another state management technique to store state, meaning it helps in storing and using values from previous requests. Whenever the user requests a web form from a web application it will get treated as a new request. an ASP.NET session will be used to store the previous requests for a specified time period.
By default, an ASP.NET session state is enabled for all ASP.NET applications. Session state data is shared across all the web pages.
Session variables are single-user global data stored on the web server, meaning by default a session state variable is stored in the web server memory and is available across all pages but it will be for a single session.
Application State
Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions.
Application state variables are also used to store data when navigating from one page to another. It's multi-user Global data meaning it will be accessible across all pages and all sessions.
An application state variable does not have any default time unlike session variables. It will end when the application hosting process is restarted or the application ends.
Session state is saved on the server, ViewState is saved in the page.
Session state is usually cleared after a period of inactivity from the user (no request happened containing the session id in the request cookies).
The view state is posted on subsequent post back in a hidden field.
SessionState
Can be persisted in memory, which makes it a fast solution. Which means state cannot be shared in the Web Farm/Web Garden.
Can be persisted in a Database, useful for Web Farms / Web Gardens.
Is Cleared when the session dies - usually after 20min of inactivity.
ViewState
Is sent back and forth between the server and client, taking up bandwidth.
Has no expiration date.
Is useful in a Web Farm / Web Garden
Caching in ASP.Net
What is Caching ?
Caching is a technique of storing frequently used data/information in memory, so that, when the same data/information is needed next time, it could be directly retrieved from the memory instead of being generated by the application.
Caching in ASP.Net
ASP.NET provides the following different types of caching:
Output Caching : Output cache stores a copy of the finally rendered HTML pages or part of pages sent to the client. When the next client requests for this page, instead of regenerating the page, a cached copy of the page is sent, thus saving time.
Data Caching : Data caching means caching data from a data source. As long as the cache is not expired, a request for the data will be fulfilled from the cache. When the cache is expired, fresh data is obtained by the data source and the cache is refilled.
Object Caching : Object caching is caching the objects on a page, such as data-bound controls. The cached data is stored in server memory.
Class Caching : Web pages or web services are compiled into a page class in the assembly, when run for the first time. Then the assembly is cached in the server. Next time when a request is made for the page or service, the cached assembly is referred to. When the source code is changed, the CLR recompiles the assembly.
Configuration Caching : Application wide configuration information is stored in a configuration file. Configuration caching stores the configuration information in the server memory.
Caching is a technique of storing frequently used data/information in memory, so that, when the same data/information is needed next time, it could be directly retrieved from the memory instead of being generated by the application.
Caching in ASP.Net
ASP.NET provides the following different types of caching:
Output Caching : Output cache stores a copy of the finally rendered HTML pages or part of pages sent to the client. When the next client requests for this page, instead of regenerating the page, a cached copy of the page is sent, thus saving time.
Data Caching : Data caching means caching data from a data source. As long as the cache is not expired, a request for the data will be fulfilled from the cache. When the cache is expired, fresh data is obtained by the data source and the cache is refilled.
Object Caching : Object caching is caching the objects on a page, such as data-bound controls. The cached data is stored in server memory.
Class Caching : Web pages or web services are compiled into a page class in the assembly, when run for the first time. Then the assembly is cached in the server. Next time when a request is made for the page or service, the cached assembly is referred to. When the source code is changed, the CLR recompiles the assembly.
Configuration Caching : Application wide configuration information is stored in a configuration file. Configuration caching stores the configuration information in the server memory.
Normalization in DBMS
Normalization is a process of organizing the data in database to avoid data redundancy, insertion anomaly, update anomaly & deletion anomaly.
Normalization
Here are the most commonly used normal forms:
First normal form(1NF)
Second normal form(2NF)
Third normal form(3NF)
Boyce & Codd normal form (BCNF)
First Normal Form
As per First Normal Form, no two Rows of data must contain repeating group of information i.e each set of column must have a unique value. Each table should be organized into rows, and each row should have a primary key that distinguishes it as unique.
Second Normal Form
A table is said to be in Second Normal Form if both the following conditions hold:
It is in first normal form.
All non-key attributes are fully functional dependent on the primary key.
Third Normal form
A table is in a third normal form when the following conditions are met −
It is in second normal form.
All non-primary fields are dependent on the primary key.
Boyce and Codd Normal Form
It is an advance version of 3NF
A database table is in BCNF if and only if there are no non-trivial functional dependencies of attributes on anything other than a superset of a candidate key.
BCNF is also sometimes referred to as 3.5NF, or 3.5 Normal Form.
Denormalization
Normalization
Here are the most commonly used normal forms:
First normal form(1NF)
Second normal form(2NF)
Third normal form(3NF)
Boyce & Codd normal form (BCNF)
First Normal Form
As per First Normal Form, no two Rows of data must contain repeating group of information i.e each set of column must have a unique value. Each table should be organized into rows, and each row should have a primary key that distinguishes it as unique.
Second Normal Form
A table is said to be in Second Normal Form if both the following conditions hold:
It is in first normal form.
All non-key attributes are fully functional dependent on the primary key.
Third Normal form
A table is in a third normal form when the following conditions are met −
It is in second normal form.
All non-primary fields are dependent on the primary key.
Boyce and Codd Normal Form
It is an advance version of 3NF
A database table is in BCNF if and only if there are no non-trivial functional dependencies of attributes on anything other than a superset of a candidate key.
BCNF is also sometimes referred to as 3.5NF, or 3.5 Normal Form.
Denormalization
Denormalization is the technique of combining the data into a single table to make data retrieval faster.
Subscribe to:
Posts (Atom)