All Type Coding

Search Here

.Net Threading

Thread in computer science means a sequence of execution instructions that can run independently , that is a single flow of execution in a process. Thread is like a process, at least one thread exists within each process. Single Thread (normal programs) in computer science means that only one task can execute and at the same time the other tasks have to wait for the completion of the current task like in a queue. Single thread resulted in systems idle time and application performance.
In .Net, the threading is handled through the 'System.Threading' namespace. Creating a variable of the System.Threading.Thread type allows you to create a new thread to start working with. It allows you to create and access individual threads in a program.Creating Thread A thread is created by creating a Thread object, giving its constructor a ThreadStart reference.

ThreadStart childthreat = new ThreadStart(childthreadcall);

 

A simple classic thread Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadStart testThreadStart = new ThreadStart(new Program().testThread);
            Thread testThread = new Thread(testThreadStart);

            testThread.Start();
            Console.ReadLine();
        }

        public void testThread()
        {
            //executing in thread
            int count = 0;
            while (count++ < 50)
            {
                Console.WriteLine("Thread Executed "+count+" times");
                Thread.Sleep(500);
            }
        }
    }
}


Output: 








Multithreading allows multiple process to execute concurrently within a single program .That is more than one task in a program can execute at the same

time and each thread run independently of its own. If multiple threads can exist within a process, typically share the state information of a process, and

share memory and other resources directly. Each thread maintains exception handlers, a scheduling priority, and a set of structures the system uses to
save the thread context until it is scheduled.


Multithreaded Programming With Classic Threads:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadStart testThread1Start = new ThreadStart(new Program().testThread1);
            ThreadStart testThread2Start = new ThreadStart(new Program().testThread2);

            Thread[] testThread = new Thread[2];
            testThread[0] = new Thread(testThread1Start);
            testThread[1] = new Thread(testThread2Start);

            foreach (Thread myThread in testThread)
            {
                myThread.Start();
            }

            Console.ReadLine();
        }

        public void testThread1()
        {
            //executing in thread
            int count = 0;
            while (count++ < 10)
            {
                Console.WriteLine("Thread 1 Executed "+count+" times");
                Thread.Sleep(1);
            }
        }

        public void testThread2()
        {
            //executing in thread
            int count = 0;
            while (count++ < 10)
            {
                Console.WriteLine("Thread 2 Executed " + count + " times");
                Thread.Sleep(1);
            }
        }
    }
}
 

Output:











Working With ThreadPool: So, as we have seen so far in above code examples, uses ‘Thread’ in raw mode. However, we can simplify the thread running process with use of  ‘ThreadPool’ class that is provided by .NET framework and is very much helpful for quick implementation of multithreaded programming. All we have to do  is to queue the function we want running in thread. And it will automatically start executing them. The following code will demonstrate this simplified usage  of ‘ThreadPool’ .


For Example:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadPool.QueueUserWorkItem(new Program().testThread1);
            ThreadPool.QueueUserWorkItem(new Program().testThread2);

            Console.ReadLine();
        }

        public void testThread1(Object threadContext)
        {
            //executing in thread
            int count = 0;
            while (count++ < 10)
            {
                Console.WriteLine("Thread 1 Executed " + count + " times");
                Thread.Sleep(100);
            }
        }

        public void testThread2(Object threadContext)
        {
            //executing in thread
            int count = 0;
            while (count++ < 10)
            {
                Console.WriteLine("Thread 2 Executed " + count + " times");
                Thread.Sleep(100);
            }
        }
    }
}

Output:

















Thread Life Cycle:
The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution.

Life cycle of a thread: The Unstarted State : It is the situation when the instance of the thread is created but the Start method is not called. The Ready State : It is the situation when the thread is ready to execute and waiting CPU cycle.    The Not Runnable State : a thread is not runnable, when:

Sleep method has been called
Wait method has been called
Blocked by I/O operations
The Dead State : It is the situation when the thread has completed execution or has been aborted.Thread Priority The Priority property of the Thread class specifies the priority of one thread with respect to other. The .Net runtime selects the ready thread with the highest priority.The priorities could be categorized as:

    Above normal
    Below normal
    Highest
    Lowest
    Normal

Once a thread is created, its priority is set using the Priority property of the thread class. 

NewThread.Priority = ThreadPriority.Lowest; 

.Net Garbage Collection

The garbage collection (GC) is new feature in Microsoft .net framework. it provides a new mechanism for releasing unreferenced objects from the memory (that is we no longer needed that objects in the program) ,this process is called Garbage Collection (GC). When it happens:
When a program creates an Object, the Object takes up the memory. Later when the program has no more references to that Object, the Object's memory becomes unreachable, but it is not immediately freed. The Garbage Collection checks to see if there are any Objects in the heap that are no longer being used by the application. If such Objects exist, then the memory used by these Objects can be reclaimed. So these unreferenced Objects should be removed from memory , then the other new Objects you create can find a place in the Heap.
The reclaimed Objects have to be Finalized later. Finalization allows a resource to clean up after itself when it is being collected. This releasing of unreferenced Objects is happening automatically in .Net languages by the Garbage Collector (GC). The programming languages like C++, programmers are responsible for allocating memory for Objects they created in the application and reclaiming the memory when that Object is no longer needed for the program. In .Net languages there is a facility that we can call Garbage Collector (GC) explicitly in the program by calling System.GC.Collect.

What is namespaces,.Net Application Domain and .Net Code Access Security.?

Namespaces are used to organize your code.it is the way to organize .NET Framework Class Library into a logical grouping according to their functionality, usability as well as category they should belong to, or we can say Namespaces are logical grouping of types for the purpose of identification.
 A good way to organize your namespaces is via a hierarchical system. You put the more general names at the top of the hierarchy and get more specific as you go down. This hierarchical system can be represented by nested namespaces.By placing code in different sub-namespaces, you can keep your code organized.

The example:

namespace india.CSharp.Namespaces
{
public class Hello
{
public string GetMessage()
{
return "Hello, world";
}
}
}

Namespaces are hierarchical, and the name india.CSharp.Namespaces is actually shorthand for defining  a namespace named arun that contains a namespace named CSharp that itself contains a namespace named Namespaces, as in:

namespace india
{
namespace CSharp
{
namespace Namespaces
{....}
}
}

The using keyword has two uses:

    Create an alias for a namespace (a using alias).
    Permit the use of types in a namespace, such that, you do not have to qualify the use of a type in that namespace (a using directive).

Implement the "using" Directive
Next, we'll write a console application that uses the Hello class. We could just use the fully qualified name for the class-india.CSharp.Namespaces.Hello-but this name is quite long and unwieldy. An easier way is to use a "using" directive, which makes it possible to use all of the types in a namespace without qualification. If you would like to call methods without typing their fully qualified name, you can implement the "using"  directive.

using sysem;
using india.CSharp.Namespaces;
class Hello
{
static void Main()
{
Hello m = new Hello ();
System.Console.WriteLine(m.GetMessage());
}
}

"using System", is the same "using" directive you have seen in every program in this article. It allows you  to type the method names of members of the "System" namespace without typing the word "System" every time. In class Hello(), "Console" is a class member of the "System" namespace with the method "WriteLine". It's fully qualified name is "System.Console.WriteLine(...)".

Note that the two occurrences of Hello are shorthand for india.CSharp.Namespaces.Hello. C# also enables the definition and use of aliases. Such aliases can be useful in situation in which name collisions occur between two libraries, or when a small number of types from a much larger namespace are being used.

Using alias directives

A using-alias-directive introduces an identifier that serves as an alias for a namespace or type within the immediately enclosing compilation unit or namespace body.

using identifier = namespace-or-type-name ;

Within member declarations in a compilation unit or namespace body that contains a using-alias-directive, the identifier introduced by the using-alias-directive can be used to reference the given namespace or type.

For example:

namespace N1.N2
{
class A {}
}
namespace N3
{
using A = N1.N2.A;
class B: A {}
}

Here, within member declarations in the N3 namespace, A is an alias for N1.N2.A, and thus class N3.B
derives from class N1.N2.A. The same effect can be obtained by creating an alias R for N1.N2 and then
referencing R.A:

namespace N3
{
using R = N1.N2;
class B: R.A {}
}

The identifier of a using-alias-directive must be unique within the declaration space of the compilation unit or namespace that immediately contains the using-alias-directive.

Using namespace directives

A using-namespace-directive imports the types contained in a namespace into the immediately enclosing compilation unit or namespace body, enabling the identifier of each type to be used without qualification.

using-namespace-directive:using namespace-name ;

Within member declarations in compilation unit or namespace body that contains a using-namespace-directive, the types contained in the given namespace can be referenced directly.

For example:

namespace N1.N2
{
class A {}
}
namespace N3
{
using N1.N2;
class B: A {}
}

Here, within member declarations in the N3 namespace, the type members of N1.N2 are directly available, and thus class N3.B derives from class N1.N2.A. Like a using-alias-directive, a using-namespace-directive does not contribute any new members to the underlying declaration space of the compilation unit or namespace, but rather affects only the compilation unit or namespace body in which it appears.

The namespace-name referenced by a using-namespace-directive is resolved in the same way as the namespace-or-type-name referenced by a using-alias-directive. Thus, using-namespace-directives in the same compilation unit or namespace body do not affect each other and can be written in any order.

Conclusion:C# programs are organized using namespaces. Using directives are provided to facilitate the use of namespaces. From this article we can understand the need and usage of Namespaces in classes.The Namespaces can hold other types also as follows:
Classes,Structures,Interfaces,Enumerations,Delegates.Namespaces are used both as an "internal" organization system for a program, and as an "external" organization system-a way of presenting program elements that are exposed to other programs.


.Net Application Domain

An application domain is a virtual process and is used to isolate applications from one another. Each application domain has their own virtual address space which scopes the resources for the application domain using that address space.

Each application running within its main process boundaries and its application domain boundaries. All objects created within the same application scope are created within the same application domain. Multiple application domains can exist in a single operating system process. An application running inside one application domain cannot directly access the code running inside another application domain.

System.AppDomain is the main class you can use to deal with application domains.


.Net Code Access Security
The .NET Security Model provides code access permissions and code identity permissions. Code Access Security is the part of the .NET security model that determines whether or not the code is allowed to run, and what resources it can use when it is running. Code Access Security policy uses evidence to help grant the right permissions to the right assembly.

An administrator can configure Code Access Security policy to restrict the resource types that code can access and the other privileged operations it can perform. Code Access Security allows code to be trusted to varying degrees depending on where the code originates and on other aspects of the code's identity. Code Access Security can also help minimize the damage that can result from security vulnerabilities in your code.

What is Manifest,GAC (Global Assembly Cache), .Net Assembly Contents.?

Manifest is a file that containing Metadata about .NET Assemblies.
Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the
following things
• Version of assembly.
• Security identity.
• Scope of the assembly.
• Resolve references to resources and classes.
The assembly manifest can be stored in a PE file either (an .exe or) .dll with Microsoft
intermediate language (MSIL code with Microsoft intermediate language (MSIL) code or in a stand-alone PE file, that contains only assembly manifest information.


GAC (Global Assembly Cache) is where all shared .NET assembly reside.Each computer on which the Common Language Runtime is installed has a machine-wide code cache called the 'Global Assembly Cache'. The Global Assembly Cache (GAC) enables you to share assemblies across numerous applications. The GAC is automatically installed with the .NET runtime. The global assembly cache is located in 'Windows/WinNT' directory and inherits the directory's access control list that administrators have used to protect the folder.

The approach of having a specially controlled central repository addresses the shared library concept and helps to avoid pitfalls of other solutions that lead to drawbacks like DLL hell. The Global Assembly Cache Tool (Gacutil.exe), that allows you to view and manipulate the contents of the Global Assembly Cache.

.Net Assembly Contents

A .NET static assembly can consist of following elements:

a) Assembly Manifest - The Metadata that describes the assembly and its contents

b) Type Metadata - Defines all types, their properties and methods.

c) MSIL - Microsoft intermediate language

d) A set of Resources - All other resources like icons, images etc.Only the assembly manifest is required, but either types or resources are needed to give the assembly in any meaningful functionality.

Metadata in .Net

Metadata is the life blood of the .NET platform.it
is binary information which describes the characteristics of a resource . This information include Description of the Assembly , Data Types and members with their declarations and implementations, references to other types and members , Security permissions etc. A module's metadata contains everything that needed to interact with another module.
During the compile time Metadata created with Microsoft Intermediate Language (MSIL) and stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE) file. During the runtime of a program Just In Time (JIT) compiler of the Common Language Runtime (CLR) uses the Metadata and converts Microsoft Intermediate Language (MSIL) into native code. When code is executed, the runtime loads metadata into memory and references it to discover information about your code's classes, members, inheritance, and so on. Moreover Metadata eliminating the need for Interface Definition Language (IDL) files, header files, or any external method of component reference.

.Net Assembly

Assembly is a logical unit of code, that contains code which the Common Language Runtime (CLR) executes.Assembly is unit of deployment like EXE or a DLL. An assembly consists of one or more files (dlls, exe’s, html files etc.), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These
resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing. An assembly is completely self-describing. An assembly contains metadata information, which is used by the CLR for everything from type checking an security to actually invoking the components methods. As all information is in the assembly itself, it is independent of registry. This is the basic advantage as
compared to COM where the version was stored in registry.
 Multiple versions can be deployed side by side in different folders. These different versions can execute at the same time without interfering with each other. Assemblies can be private or shared. For private assembly deployment, the assembly is copied to the same directory as the client program that references it. No registration is needed, and no fancy installation program is required. When the
component is removed, no registry cleanup is needed, and no uninstall program is
required. Just delete it from the hard drive.  In shared assembly deployment, an assembly is installed in the Global Assembly Cache (or GAC). The GAC contains shared assemblies that are globally accessible to all .NET applications on the machine.


Types of Assembly:
There are two types of assembly
1- Private :A private assembly is normally
used by a single application, and is stored in the application's directory, or a sub-directory beneath.
2-and Public assembly.
A shared Assembly is one that can be referenced by more than one application. If multiple applications need to access an Assembly, we should add the Assembly to the Global Assembly Cache (GAC). There is also a third and least known type of an assembly: Satellite Assembly . A Satellite Assembly contains only static objects like images and other non-executable files required by the application.

Difference between NameSpace and Assembly?
A .Net Namespace provides the fundamental unit of logical code grouping while an assembly provides a fundamental unit of physical code grouping.
Namespace can span multiple assembly.

How to Add an assembly to GAC.?
    We can use Gacutil.exe to add strong-named assemblies to the global assembly cache.Type the following at the command prompt.

gacutil -i AssemblyName


AssemblyName name is the name of the assembly to install in the global assembly cache.We can use another option to install assembly in GAC by using Microsoft Windows Installer. This is the recommended and most common way to add assemblies to the global assembly cache.

How to remove an Assembly from GAC ?
At the command prompt type the following to remove the Assembly from GAC.

gacutil /u  AssemblyName (Fully Qualified Name of Assembly)
For Example

gacutil /u "assemblyname,Version=2.0.0.0, Culture=neutral, PublicKeyToken=0213456789ABCDEF"



How to see assembly version in c# .net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication1
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The version of the currently executing assembly is: {0}",
                          typeof(Program).Assembly.GetName().Version);
            Console.ReadKey();
        }
    }
}
 

Output:
 


What is a Managed Code?

Managed Code in Microsoft .Net Framework, is the code to identify computer program source code that requires and will execute only under the management of a Common Language Runtime virtual machine.In short, all IL are
managed code. However, if you are using some third party software example VB6 or VC++
component they are unmanaged code, as .NET runtime (CLR) does not have control over the
source code execution of these languages.
Unmanaged code is compiled to machine code and therefore executed by the OS directly.
The benefits of Managed Code include programmers convenience and enhanced security . Managed code is designed to be more reliable and robust than unmanaged code , examples are Garbage Collection , Type Safety etc.

Just In Time Compiler (JIT)

JIT (Just In Time Compiler) compiler runs after the program has started and compiles the code (usually bytecode or some kind of VM instructions) on the fly (or just-in-time, as it's called) into a form that's usually faster, typically the host CPU's native instruction set.During the code execution time, the Managed Code compiled only when it is needed, that is it converts the appropriate instructions to the native code for execution just before when each function is called. This process is called Just In Time (JIT) compilation, also known as Dynamic Translation .The Common Language Runtime (CLR) provides various Just In Time compilers (JIT) and each works on a different architecture depending on Operating System. That is why the same Microsoft Intermediate Language (MSIL) can be executed on different Operating Systems without rewrite the source code. JIT compilation preserves memory and save time during application initialization. JIT compilation is used to run at high speed, after an initial phase of slow interpretation.

Microsoft Intermediate Language(MSIL)

We can call it as Intermediate Language (IL) or Common Intermediate Language (CIL). When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code.
During the runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler converts the Microsoft Intermediate Language (MSIL) code into native code to the Operating System.
MSIL produces metadata. MSIL and metadata are contained in a portable executable(PE) file.
MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations


Portable executable -The file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR. 

Common Language Specification (CLS)

It is a sub set of CTS and it specifies a set of rules that needs to be adhered or satisfied by all language compilers targeting CLR.
Common language specification Rules:
 It describes the minimal and complete set of features to produce code that can be hosted by CLR.
Sample Rules:
1.        Internal representation of enumerations

2.       Representation of text strings

3.       Definition of static members and this is a subset of the CTS which all .NET languages are expected to support.

4.   Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.
Common Language Specification (CLS) is a set of basic language features that .Net Languages needed to develop Applications and Services , which are compatible with the .Net Framework. When there is a situation to communicate Objects written in different .Net Complaint languages , those objects must expose the features that are common to all the languages . Common Language Specification (CLS) ensures complete interoperability among applications, regardless of the language used to create the application.

Common Language Specification (CLS) defines a subset of Common Type System (CTS) . Common Type System (CTS) describes a set of types that can use different .Net languages have in common , which ensure that objects written in different languages can interact with each other.

Common Type System - CTS

 CTS describes a set of types that can be used in different .Net languages in common . That is , the Common Type System (CTS) ensure that objects written in different .Net languages can interact with each other. For Communicating between programs written in any .NET complaint language, the types have to be compatible on the basic level .The common type system supports two general categories of types: 

1-Value Types
2-Reference Types


The Value Types are passed by values and stored in the stack. The Reference Types are passed by references and stored in the heap. Common Type System (CTS) provides base set of Data Types which is responsible for cross language integration. The Common Language Runtime (CLR) can load and execute the source code written in any .Net language, only if the type is described in the Common Type System (CTS) .Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types.

.Net Framework Class Library (FCL)

The .Net Framework Class Library (FCL) includes a huge collection of reusable classes , interfaces, and value types that expedite and optimize the

development process and provide access to system functionality.This is also called as Base Class Library and it is common for all types of applications
The following are different types of applications that can make use of .net class library.

1. Windows Application.
2. Console Application
3. Web Application.
4. XML Web Services.
5. Windows Services.
 

The .Net Framework class library (FCL) organized in a hierarchical tree structure and it is divided into Namespaces. Namespaces is a logical grouping of

types for the purpose of identification. Framework class library (FCL) provides the consistent base types that are used across all .NET enabled languages.

The Classes are accessed by namespaces, which reside within Assemblies. The System Namespace is the root for types in the .NET Framework.

Common Language Runtime in .net framework

Common Language Runtime (CLR)

.Net Framework provides runtime environment called Common Language Runtime (CLR). It works as a layer between Operating Systems and the applications written in .Net languages that conforms to the Common Language Specification (CLS). 

















It provides an environment to run all the .Net Programs. The code which runs under the CLR is called as Managed Code. Programmers need not to worry on managing the memory if the programs are running under the CLR as it provides memory management and thread management.
Programmatically, when our program needs memory, CLR allocates the memory for scope and de-allocates the memory if the scope is completed.
Language Compilers (for example. C#, VB.Net, J#) will convert the Code/Program to Microsoft Intermediate Language (MSIL) intern this will be converted to Native Code by CLR.
The runtime provides the following benefits:
   

    Performance improvements.

    The ability to easily use components developed in other languages.

    Extensible types provided by a class library.

    Language features such as inheritance, interfaces, and overloading for object-oriented programming.

    Support for explicit free threading that allows creation of multithreaded, scalable applications.

    Support for structured exception handling.

    Support for custom attributes.

    Garbage collection.

    Use of delegates instead of function pointers for increased type safety and security. 

What are the functions of Microsoft .Net Framework.?

When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Before code can be run, MSIL must be converted to CPU-specific code, usually by a just-in-time (JIT) compiler. When a compiler produces MSIL, it also produces metadata.



 Metadata is completely self-describing . Metadata is stored in a file called Manifest, and it contains information about the members, types, references and all the other data that the Common Language Runtime (CLR) needs for execution .The Common Language Runtime (CLR) uses metadata to locate and load classes, generate native code, provide security, and execute Managed Code. Both Microsoft Intermediate Language (MSIL) and Metadata assembled together is known as Portable Executable (PE) file. Portable Executable (PE) is supposed to be portable across all 32-bit operating systems by Microsoft .Net Framework.

During the runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler converts the Microsoft Intermediate Language (MSIL) code into native code to the Operating System. The native code is Operating System independent and this code is known as Managed Code , that is, the language's functionality is managed by the .NET Framework . The Common Language Runtime (CLR) provides various Just In Time (JIT) compilers, and each works on a different architecture depends on Operating Systems, that means the same Microsoft Intermediate Language (MSIL) can be executed on different Operating Systems. From the following section you can see how Common Language Runtime (CLR) functions .

What is Microsoft .Net Framework

.NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs primarily on Microsoft Windows.
Microsoft .Net Framework is a platform that provides tools and technologies you need to build Networked Applications as well as Distributed Web Services and Web Applications. The .Net Framework provides the necessary compile time and run-time foundation to build and run any language that conforms to the Common Language Specification (CLS).The main two components of .Net Framework are Common Language Runtime (CLR) and .Net Framework Class Library (FCL).

























 .NET Framework includes a large class library known as Framework Class Library (FCL) and provides language interoperability  across several programming languages.The Common Language Runtime (CLR) is the runtime environment of the .Net Framework , that executes and manages all running code like a Virtual Machine.

History of .net framework,version history of .NET,features history of .net framework

The .NET Framework is an essential technology for ASP.NET development. it is a software development platform developed by Microsoft. It runs on Microsoft Windows OS. .NET provides tools and libraries that allow developers to develop applications and services much easily, faster and secure by using a convenient way.
History of .net framework


A potentially dangerous Request.Form value was detected from the client/A potentially dangerous Request.Form value was detected" when updating content with HTML tags


Here are possible solution which may help you. Make server side configuration setting for this. If you want to allow HTML element as input from selected pages in your project than you set this page attribute.

<%@ Page ValidateRequest="false" %>

This ValidateRequest="false" on each page. If you want in all pages in you project than make changes in Web.Config file. Add this tag In section.

If you are using .Net 4.0 than you have to make one more change in Web.Config file. Add this tag In section.

<httpRuntime requestValidationMode="2.0" />

Here are configuration for do not validate request for all pages in .Net 4.0

<configuration>
  <system.web>
     <httpRuntime requestValidationMode="2.0" />
    <pages enableSessionState="true" validateRequest="false"/>
  </system.web> 
</configuration>


What is ASP.NET

ASP.NET is a Web application framework developed by Microsoft to build dynamic data driven Web applications and Web services. using HTML, CSS and JavaScript. Moreover, it is a technology for developing, deploying, and running Web applications. ASP.NET is a part of the Microsoft .NET Framework, so all .NET Framework features are available to ASP.NET applications. That means, when you developing ASP.NET applications you have access to classes in the .NET Framework because .NET framework is a collection of classes and ASP.NET is the successor to classic ASP (Active Server Pages).

ASP.NET introduces entirely a new object-oriented execution model. In order to overcome the limitations of ASP (Active Server Pages) , Microsoft has developed a new technology called Microsoft ASP.NET 
ASP.NET is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code using any supported .NET languages like VB.NET and C#. Unlike the ASP runtime, ASP.NET uses the Common Language Runtime (CLR) provided by the .NET Framework. The Microsoft .NET Platform provides all of the tools and technologies that are needed to build distributed Web applications. ASP.NET is integrated with Visual Studio .NET, which provides a GUI designer, a rich toolbox, and a fully integrated debugger. In ASP.NET, you can write the HTML code in the .aspx file and the code for programming logic in the code-behind file (.aspx.vb or .aspx.cs ). Also ASP.NET introduces two sets of controls, the HTML controls and the Web controls, which are collectively known as "server controls."

What is a Web Application?
A web application is an application that is accessed by users using a web browser. Examples of web browsers include 
1. Microsoft Internet Explorer
2. Google Chrome
3. Mozilla FireFox
4. Apple Safari
5. Netscape Navigator

Built in string function LEFT, RIGHT, CHARINDEX and SUBSTRING,Replicate, Space, Patindex, Replace and Stuff in sql server


Let us assume we have table user as shown below. 

LEFT(Character_Expression, Integer_Expression) - Returns the specified number of characters from the left hand side of the given string.
forExample:

select left(FirstName,3)FirstName,left(LastName,3)LastName,left (Email,3)Email,left(cast(DOB as date),4)DOB from Users

Output:














RIGHT(Character_Expression, Integer_Expression) - Returns the specified number of characters from the right hand side of the given character expression.
forExample:

select right(FirstName,3)FirstName,right(LastName,3)LastName,right(Email,3)Email,right(cast(DOB as date),2)DOB from Users
Output:















CHARINDEX('Expression_To_Find', 'Expression_To_Search', 'Start_Location') - Returns the starting position of the specified expression in a character string. Start_Location parameter is optional.
forExample:
select charindex('@',Email,1)Indexof@ from Users where ID=1


Output=4


SUBSTRING('Expression', 'Start', 'Length') - As the name, suggests, this function returns substring (part of the string), from the given expression. You specify the starting location using the 'start' parameter and the number of characters in the substring using 'Length' parameter. All the 3 parameters are mandatory.
forExample:

select substring(FirstName,1,1)FirstName,substring(LastName,1,3)LastName,substring(Email,1,CHARINDEX('@',Email,1)-1)Email,left(cast(DOB as date),4)DOB  from Users

Output:
















REPLICATE(String_To_Be_Replicated, Number_Of_Times_To_Replicate) - Repeats the given string, for the specified number of times.
forExample:
Select FirstName, LastName, SUBSTRING(Email, 1, 2) + REPLICATE('*',5) + SUBSTRING(Email, CHARINDEX('@',Email), LEN(Email) - CHARINDEX('@',Email)+1) as Email from Users

Output:















REPLACE(String_Expression, Pattern , Replacement_Value)
Replaces all occurrences of a specified string value with another string value.
forExample:
Select Email, REPLICATE(Email, '.com', '.net') as ConvertedEmail from Users

Output:















SPACE(Number_Of_Spaces) - Returns number of spaces, specified by the Number_Of_Spaces argument.
forExample:
Select FirstName + SPACE(5) + LastName as FullName 
from Users
 where ID=1

Output:






PATINDEX('%Pattern%', Expression)
Returns the starting position of the first occurrence of a pattern in a specified expression. It takes two arguments, the pattern to be searched and the expression. PATINDEX() is simial to CHARINDEX(). With CHARINDEX() we cannot use wildcards, where as PATINDEX() provides this capability. If the specified pattern is not found, PATINDEX() returns ZERO.
forExample:
Select 
Email, PATINDEX('%@gmail.com', Email) as FirstOccurence 
from Users 
where PATINDEX('%@gmail.com', Email) >4

Output:







STUFF(Original_Expression, Start, Length, Replacement_expression)
STUFF() function inserts Replacement_expression, at the start position specified, along with removing the charactes specified using Length parameter.
forExample:
Select 
FirstName, LastName,Email, STUFF(Email, 2, 3, '*****') as StuffedEmail 
from Users
 where ID in (1,2,3)

Output:




Built in string functions in sql server



In SQL server, Function can be broadly divided into 2 categoris 1. Built-in functions 2. User Defined functions

Here we will look at the most common string functions available .There are several built-in functions..in sql server.
















ASCII(Character_Expression) - Returns the ASCII code of the given character expression.
To find the ASCII Code of capital letter 'A'
Example:
Select ASCII('A')
Output: 65

CHAR(Integer_Expression) - Converts an int ASCII code to a character. The Integer_Expression, should be between 0 and 255.
for example: 

Declare @Number int
Set @Number = 1
While(@Number <= 1255)
Begin
select CHAR(@Number)
Set @Number = @Number + 1
End
output:


A B C D E F G H I J K L M N O P Q R S T U V W X Y Z


Printing uppercase alphabets using CHAR() function:

Declare @Number int
Set @Number = 65
While(@Number <= 90)
Begin
 Print CHAR(@Number)
 Set @Number = @Number + 1
End

Printing lowercase alphabets using CHAR() function:

Declare @Number int
Set @Number = 97
While(@Number <= 122)
Begin
 Print CHAR(@Number)
 Set @Number = @Number + 1
End


Another way of printing lower case alphabets using CHAR() and LOWER() functions.

Declare @Number int
Set @Number = 65
While(@Number <= 90)
Begin
 Print LOWER(CHAR(@Number))
 Set @Number = @Number + 1
End

LTRIM(Character_Expression) - Removes blanks on the left handside of the given character expression.


Example: Removing the 3 white spaces on the left hand side of the '   Hello' string using LTRIM() function.

Select LTRIM('   Hello')
Output: Hello

RTRIM(Character_Expression) - Removes blanks on the right hand side of the given character expression.


Example
: Removing the 3 white spaces on the left hand side of the 'Hello   ' string using RTRIM() function.
Select RTRIM('Hello   ')
Output: Hello

Example: To remove white spaces on either sides of the given character expression, use LTRIM() and RTRIM() as shown below.

Select LTRIM(RTRIM('   Hello   '))
Output: Hello

LOWER(Character_Expression) - Converts all the characters in the given Character_Expression, to lowercase letters.


Example: Select LOWER('CONVERT This String Into Lower Case')

Output: convert this string into lower case

UPPER(Character_Expression) - Converts all the characters in the given Character_Expression, to uppercase letters.

Example: Select UPPER('CONVERT This String Into upper Case')
Output: CONVERT THIS STRING INTO UPPER CASE

REVERSE('Any_String_Expression') - Reverses all the characters in the given string expression.

Example: Select REVERSE('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
Output: ZYXWVUTSRQPONMLKJIHGFEDCBA

LEN(String_Expression) - Returns the count of total characters, in the given string expression, excluding the blanks at the end of the expression.


Example: Select LEN('SQL Functions   ')

Output: 13