public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection Files { get; set; }
public IList FileAttachments { get; set; }
}
public class FileAttachment
{
public int UserId { get; set; }
public string Name { get; set; }
public string ContentType { get; set; }
}
Controller
public class HomeController : Controller
{
private string SavePath = "C:\\TempFile";
public ActionResult Index()
{
var userModel = new UserModel();
return View(userModel);
}
[HttpPost]
public ActionResult Index(UserModel userModel)
{
var attachements = new List();
Directory.CreateDirectory(SavePath);
if (userModel.Files != null)
{
foreach (var file in userModel.Files)
{
// Set the name of the file to upload.
string extension = Path.GetExtension(file.FileName);
string fileName = String.Concat(DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid(), extension);
//save file
file.SaveAs(Path.Combine(SavePath, fileName));
attachements.Add(new FileAttachment()
{
UserId = userModel.Id,
Name = fileName,
ContentType = file.ContentType
});
}
userModel.FileAttachments = attachements;
}
return View(userModel);
}
public FileResult Download(FileAttachment fileAttachment)
{
var cd = new System.Net.Mime.ContentDisposition
{
FileName = fileAttachment.Name,
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(Path.Combine(SavePath, fileAttachment.Name), fileAttachment.ContentType);
}
}
Design Patterns in .NetIntroductionThe concept of a ‘Software Design Pattern’ was adopted from the idea of a building design pattern in the field of building design and architecture. Within the context of software engineering, a Design Pattern is the official term given to a design concept that encompasses the idea of reuse and communication. Simply stated, Design Patterns are tried and tested solutions to common and recurring challenges. At their core, design patterns are the manifestation of good object-oriented design principles. Design Patterns are important to understand for the following reasons: They give us reuse
Once a design pattern has emerged to solve a particular problem, that design pattern can be applied countless times on future tasks where a similar problem may arise. It can also be used by countless others who may encounter similar problems.
The give us a common taxonomy allowing for better communication
Design patterns allow one to refer to a design concept without explaining the full detail of that concept. How often has one heard a conversation along the lines of the following? They give us a higher level of abstraction in terms of analysis and design This allows one to think of the larger design in terms of smaller component areas. Therefore, when one looks at the bigger picture, one can visualize it in terms of its constituent parts. Fosters design thinking
Creational PatternsFactory Pattern In .NET Factory pattern is one of the types of creational patterns. You can make out from the name factory itself it’s meant to construct and create something. In software architecture world factory pattern is meant to centralize creation of objects. Factory Method Pattern defines an interface for creating an object, but let subclasses decide which class to instantiate. Below is a code snippet of a client which has different types of invoices. These invoices are created depending on the invoice type specified by the client. Advantages: Remove lots of ‘new’ keyword scattered in the client. Client code is aware of both the concrete classes i.e. ‘InvoiceWithHeader’ and ‘InvoiceWithOutHeader’. To remove this issue we have introduced a common interface ‘IInvoice’. Both the concrete classes ‘InvoiceWithHeader’ and ‘InvoiceWithOutHeader’ inherit and implement the ‘IInvoice’ interface. In order to avoid recompiling the client we have introduced the invoice interface ‘IInvoice’. Both the concrete classes ‘InvoiceWithOutHeaders’ and ‘InvoiceWithHeader’ inherit and implement the ‘IInvoice’ interface. public interface IInvoice { void Print(); } public class InvoiceWithHeader : IInvoice { public void Print() { Console.WriteLine("Invoice With Header."); } } public class InvoiceWithOutHeader : IInvoice { public void Print() { Console.WriteLine("Invoice Without Header."); } } public class FactoryInvoice { static public IInvoice GetInvoice(int invoiceType) { IInvoice _invoice; if (invoiceType == 1) _invoice = new InvoiceWithHeader(); else if (invoiceType == 2) _invoice = new InvoiceWithOutHeader(); else return null; return _invoice; } } class Program { static void Main(string[] args) { IInvoice _invoice; Console.WriteLine("Enter Invoice Type:"); int invoiceType = Convert.ToInt32(Console.ReadLine()); _invoice = FactoryInvoice.GetInvoice(invoiceType); _invoice.Print(); } } Abstract Factory Pattern In .NET Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. Abstract factory helps us to unite similar factory pattern classes in to one unified interface. So basically all the common factory patterns now inherit from a common abstract factory class which unifies them in a common class. We can practically implement abstract factory in actual code. We have scenario where we have UI creational activities for textboxes and buttons through their own centralized factory classes ‘FactoryButton’ and ‘FactoryText’. Both these classes inherit from common interface ‘InterfaceRender’. Both the factories ‘FactoryButton’ and ‘FactoryText’ inherits from the common factory ‘AbstractFactory’. Figure ‘Example for AbstractFactory’ shows how these classes are arranged and the client code for the same. One of the important points to be noted about the client code is that it does not interact with the concrete classes. For object creation it uses the abstract factory ( AbstractFactory ) and for calling the concrete class implementation it calls the methods via the interface ‘InterfaceRender’. So the ‘AbstractFactory’ class provides a common interface for both factories ‘FactoryButton’ and ‘FactoryText’.
Figure ‘Common Interface for concrete classes’ how the concrete classes inherits from a common interface ‘InterFaceRender’ which enforces the method ‘render’ in all the concrete classes. public interface IInterfaceRender { void Render(); } public class TextBox : IInterfaceRender { public void Render() { Console.WriteLine("The Textbox is Rendered."); } } public class Button : IInterfaceRender { public void Render() { Console.WriteLine("The Button is Rendered."); } } Factory pattern classes inherit from abstract factory. public abstract class AbstractFactory { static public IInterfaceRender GetUIObject(int objectType) { if (objectType == 1) return FactoryTextBox.GetTextBoxObject(); else return FactoryButton.GetButtonObject(); } } public class FactoryTextBox : AbstractFactory { static public IInterfaceRender GetTextBoxObject() { return new TextBox(); } } public class FactoryButton : AbstractFactory { static public IInterfaceRender GetButtonObject() { return new Button(); } } The final thing is the client code which uses the interface ‘InterfaceRender’ and abstract factory ‘AbstractFactory’ to call and create the objects. One of the important points about the code is that it is completely isolated from the concrete classes. Due to this any changes in concrete classes like adding and removing concrete classes does not need client level changes. class Program { static void Main(string[] args) { IInterfaceRender objUIObject; Console.WriteLine("Enter which object you want to render:"); int objectType = Convert.ToInt32(Console.ReadLine()); objUIObject = AbstractFactory.GetUIObject(objectType); objUIObject.Render(); } } Builder Pattern In .NET Builder pattern helps us to separate the construction of a complex object from its representation so that the same construction process can create different representations. Builder pattern is useful when the construction of the object is very complex. The main objective is to separate the construction of objects and their representations. If we are able to separate the construction and representation, we can then get many representations from the same construction. Now let’s take a real time example in software world to see how builder can separate the complex creation and its representation. Consider we have application where we need the same report to be displayed in either ‘PDF’ or ‘EXCEL’ format. Figure ‘Request a report’ shows the series of steps to achieve the same. Depending on report type a new report is created, report type is set, headers and footers of the report are set and finally we get the report for display.
Now let’s take a different view of the problem as shown in figure ‘Different View’. The same flow defined in ‘Request a report’ is now analyzed in representations and common construction. The construction process is same for both the types of reports but they result in different representations.
We will take the same report problem and try to solve the same using builder patterns. There are three main parts when you want to implement builder patterns. Builder - Builder is responsible for defining the construction process for individual parts. Builder has those individual processes to initialize and configure the product. Director - Director takes those individual processes from the builder and defines the sequence to build the product. Product - Product is the final object which is produced from the builder and director coordination. Figure ‘Builder classes in actual code’ shows the methods of the classes. To generate report we need to first Create a new report, set the report type (to EXCEL or PDF) , set report headers , set the report footers and finally get the report. We have defined two custom builders one for ‘PDF’ (ReportPDF) and other for ‘EXCEL’ (ReportExcel). These two custom builders define there own process according to the report type. The third component in the builder is the product (Report) public class Report { public string reportType; private ArrayList objHeader = new ArrayList(); private ArrayList objFooter = new ArrayList(); public void SetReportHeader(string date) { } public void SetReportFooter(string date) { } public void DisplayReport() { } } We have defined two custom builders one for ‘PDF’ (ReportPDF) and other for ‘EXCEL’ (ReportExcel). public abstract class ReportBuilder { protected Report _report; public void CreateNewReport() { } public abstract void SetReportType(); public abstract void SetReportHeader(); public abstract void SetReportFooter(); public Report GetReport() { return new Report(); } } public class ReportPDF : ReportBuilder { public override void SetReportType() { } public override void SetReportHeader() { } public override void SetReportFooter() { } } public class ReportExcel : ReportBuilder { public override void SetReportType() { } public override void SetReportHeader() { } public override void SetReportFooter() { } } Class ‘Director’ takes the builder and calls the individual method process in a sequential manner. So director is like a driver who takes all the individual processes and calls them in sequential manner to generate the final product, which is the report in this case. Figure ‘Director in action’ shows how the method ‘MakeReport’ calls the individual process to generate the report product by PDF or EXCEL. public class Director { public Report MakeReport(ReportBuilder reportBuilder) { reportBuilder.CreateNewReport(); reportBuilder.SetReportType(); reportBuilder.SetReportHeader(); reportBuilder.SetReportFooter(); return reportBuilder.GetReport(); } } Now let’s take a top view of the builder project. Figure ‘Client,builder,director and product’ shows how they work to achieve the builder pattern. Client creates the object of the director class and passes the appropriate builder to initialize the product. Depending on the builder the product is initialized/created and finally sent to the client. class Program { static void Main(string[] args) { Report _report = new Report(); Director _director = new Director(); ReportPDF reportPDF = new ReportPDF(); _report = _director.MakeReport(reportPDF); _report.DisplayReport(); ReportExcel reportExcel = new ReportExcel(); _report = _director.MakeReport(reportExcel); _report.DisplayReport(); } }
Structural Patterns Proxy Design Pattern In .NET Reference: http://aspalliance.com/827_Gang_of_Four_GOF_Design_Patterns.6 The Proxy design pattern shows a way to do just-in-time loading of objects that would consume too much memory to keep around or take too much time to load. This can be a very useful pattern for many applications. A good example of this pattern is in Microsoft Office. When you open a large Word document that has many embedded pictures, Office does not load them all at the time you open the document. As you scroll down, Office will pull the pictures from the disk file and insert them into the document. You can see this by scrolling very fast down the document. It takes a second or so for the document to “catch up” to you and show the visible images. For our example, we will have a part object that represents a manufacturer's part in a database. It has a FullDescription property that could be many pages of text. We do not want to load this text unless the user really wants to see it. We first start by creating a wrapper for the description. It is a very simple object that just exposes the text we want to return. In a real world application the text would come from a database or something similar. public class PartDescription { private string _PartNumber; private string _PartText; public PartDescription(string PartNumber) { _PartNumber = PartNumber; //load text now For the demo, we just make sometext up. if (_PartNumber == "1") { _PartText = "Pages of text for part1"; } else if (_PartNumber == "2") { _PartText = "Pages of text for part2"; } else { _PartText = "Part Not Found"; } } public string ReturnText { get { return _PartText; } } } The Part class is also simple. It just allows entry of the part number and then has a method to return the part text. The interesting method is FullDescription. You will see that the get method first checks to see if the _PartDescription object is null or not. If not, then we do not need to create the object as it has already been done before. If we do not need the text after the call, we can set the object to null after returning the text. This would be useful if we did not want to keep the overhead of the part text around. After passing the text to some other program, we can clear it in our object. Here is the rewrite of the function. public class Part { private string _PartNumber; private PartDescription _PartDescription; public Part() { _PartDescription = null; } public string PartNumber { get { return _PartNumber; } set { _PartNumber = value; } } public string FullDescription { get { if (_PartDescription == null) { _PartDescription = new PartDescription(_PartNumber); } return _PartDescription.ReturnText; } } } We have added error handling in this function to allow for a finally block to null the object.
Behavioral PatternsCommand Pattern in .NETThe command pattern is a very useful pattern when you want to give your users the ability to do certain things and undo them. Typical examples are the undo and redo on many programs today. This functionality is accomplished with the command pattern. The GOF book says to use a command pattern when: 1. Parameterize objects by an action to perform 2. Specify, queue, and execute requests at different times 3. Support undo (GOF235) The pattern encapsulates the commands of your application to self contained classes. For our example, we will revisit the dog example I have used before and play God for a while. Our operations will be to magically increase and decrease our bulldog's age. Since we are almighty, we of course can change our minds and undo our meddling. First we start with a very simple Bulldog class. public class CBulldog { private int _Age; private string _BarkString; public CBulldog() { _Age = 0; _BarkString = "Woof"; } public void Bark() { Console.WriteLine(_BarkString); } public int MyAge { get { return _Age; } set { _Age = value; } } public string MyBark { get { return _BarkString; } set { _BarkString = value; } } } All the class does is to keep up with the dog’s age, provide a method to change it and allows for the dog to bark. The bark method writes the dog's bark out to the console window. For our command classes, we first define three interfaces then our main command classes. The interfaces allow different kinds of commands to be acted upon as the same type of class. For our example, we will use two different commands, one to change the dog’s age and another to change how he barks. First we create our interfaces: public interface IBaseCommand { void Undo(); } public interface IAgeCommand : IBaseCommand { void AddAge(int age); } public interface IBarkCommand : IBaseCommand { void ChangeBark(string Newbark); } We base the two main command interfaces of a generic one that allows for an undo. This will allow us to iterate over all interfaces later and undo them as a group. We can cast any IAgeCommand or IBarkCommand down to an IBaseCommand. Now for our two classes that encapsulate the commands. They are pretty straight forward. Each takes a parameter of the dog to operate on in the constructor and saves off any relevant information like the last age, etc. public class AgeCommand : IAgeCommand { private CBulldog _OurDog; private int _OldAge; public AgeCommand(CBulldog o) { _OurDog = o; //dog to work on } public void AddAge(int age) { _OldAge = _OurDog.MyAge; _OurDog.MyAge = age; } public void Undo() { _OurDog.MyAge = _OldAge; } } public class BarkCommand : IBarkCommand { private CBulldog _OurDog; private string _OldBark; public BarkCommand(CBulldog o) { _OurDog = o; //dog to work on } public void ChangeBark(string Newbark) { _OldBark = _OurDog.MyBark; _OurDog.MyBark = Newbark; } public void Undo() { _OurDog.MyBark = _OldBark; } } Our test of the code will be to create a dog, show its initial settings, change them, show the new settings and then revert back to the original. For simplicity, we store the list of used commands in an ArrayList object. class Program { static void Main(string[] args) { CBulldog oDog; ArrayList cmd = new ArrayList(); oDog = new CBulldog(); AgeCommand a1 = new AgeCommand(oDog); Console.WriteLine(oDog.MyAge.ToString()); a1.AddAge(4); cmd.Add(a1); Console.WriteLine(oDog.MyAge.ToString()); BarkCommand b1 = new BarkCommand(oDog); oDog.Bark(); b1.ChangeBark("Yip Yip"); cmd.Add(b1); oDog.Bark(); //at this point we have a dog that as beenchanged //we also have an array that has the command //objects that were used for the change. //To undo, just loop through the arraylistbackwards cmd.Reverse(); foreach (IBaseCommand bse in cmd) { bse.Undo(); } oDog.Bark(); Console.WriteLine(oDog.MyAge.ToString()); } }
Strategy Pattern in .NETFrequently with applications, many of the operations they perform are dynamic depending on several factors. Think about a common scenario, Sales Tax. Tax amounts are based off the place where you live. There are many different tax rates in each country. A good method of implementing dynamic patterns like taxes is needed. The strategy pattern covers this gap for us. The strategy pattern is very useful when a dynamic formula or data is needed. In our situation it will allow us to swap out different tax objects when needed. The pattern lets a class take on many different behaviors depending on the context in which it is used. The strategy patterns starts with an interface that defines the methods that each different behavior defines. Our tax interface is simple, only one method that returns the (full amount of the price) * (the tax amount). public interface ITaxStrategy { double CalculateTax(double amount); } This interface will be implemented in all of our tax strategy classes to give them a common base. Two simple classes are then created for calculating taxes for the USA and the UK. Both tax rates are made-up, 5% for the USA and 7% for the UK. public class USATax : ITaxStrategy { public USATax() { } public double CalculateTax(double amount) { return amount * 1.05; } } public class UKTax : ITaxStrategy { public UKTax() { } public double CalculateTax(double amount) { return amount * 1.07; } } To demonstrate the use of the two classes, we will create a simple inventory item class that represents an item in our stores inventory. The class will hold the price of the item. public class InventoryItem { private ITaxStrategy _ItemTax; private double _ItemAmount; public InventoryItem() { } public void SetTax(ITaxStrategy tax) { _ItemTax = tax; } public double ItemAmount { get { return _ItemAmount; } set { _ItemAmount = value; } } public double ItemWithTax { get { return _ItemTax.CalculateTax(_ItemAmount); } } } Now let us examine the code that makes the class use the strategy pattern. A private variable named _ItemTax is declared as type ITaxStrategy. This is our internal representation of which strategy we want the class to use. The SetTax method allows us to set whichever strategy object we need to the inventory item. The property ItemWithTax returns the item’s amount with the tax added into it by calling the CalculateTax method on our strategy object. To see the classes in motion the following code can be used. class Program { static void Main(string[] args) { InventoryItem itm; itm = new InventoryItem(); itm.ItemAmount = (double)10; USATax usaTax; usaTax = new USATax(); UKTax ukTax; ukTax = new UKTax(); itm.SetTax(usaTax); Console.WriteLine(itm.ItemWithTax.ToString()); itm.SetTax(ukTax); Console.WriteLine(itm.ItemWithTax.ToString()); } } The first thing we do is create an object of the InventoryItem class. We then create a US tax object and a UK tax object. After setting the tax object to our inventory class, the message boxes show the result. You will get 10.5 for the first tax and 10.7 for the second, showing the different strategies in action. While this is just a demonstration, in a real world application the tax objects would be created dynamically based on a registry key, configuration file, or based on the findings of a reflection call. One technique I have used is to use reflection to query the install directory for a class that implements the ITaxStrategy interface. When the product is installed, the user chooses what region they are in and the correct dll with the tax class is installed. Reflection can then find this class and create an instance of it on the fly to pass to the inventory class.
Visitor Design Pattern In .NETReference: http://aspalliance.com/827_Gang_of_Four_GOF_Design_Patterns.3 The visitor design pattern is very useful in situations in which normal polymorphism will not work because we have fundamentally different objects, with different interfaces, that you want to work on your concrete main object. The pattern is used to give us a way to do these different operations on the object. According to the GOF book, you use the visitor pattern when: An object structure contains many classes of objects with differing interfaces and you want to perform operations on these objects that depend on their concrete classes. Many distinct and unrelated operations need to be performed on objects in an object structure and you want to avoid "polluting" their classes with these operations. Visitor lets you keep related operations together by defining them in one class. When the object structure is shared by many applications, use Visitor to put operations in just those applications that need them. The classes defining the object structure rarely change, but you often want to define new operations over the structure. Changing the object structure classes requires redefining the interface to all visitors, which is potentially costly. If the object structure classes change often, then it is probably better to define the operations in those classes (GOF333). We first start by defining a base class for our visitor object collection. We will use our common Cbulldog object for our example. public class BaseVisitor { public BaseVisitor() { } public virtual void VisitBulldog(CBulldog dog){} } The code is pretty simple, having only a single method that takes an instance of the bulldog to work on. We can then derive concrete instances of visitors from this base. We will derive two for our example, one that changes our dog’s age and another that changes his bark. First we will look at our Cbulldog class. It has not changed much; there is only one new method. public class CBulldog { private int _Age; private string _BarkString; public CBulldog() { _Age = 0; _BarkString = "Woof"; } public void TakeVisitor(BaseVisitor bv) { bv.VisitBulldog(this); } public void Bark() { Console.WriteLine(_BarkString); } public int MyAge { get { return _Age; } set { _Age = value; } } public string MyBark { get { return _BarkString; } set { _BarkString = value; } } } The TakeVisitor method allows our class to accept any visitor that is derived from BaseVisitor. The method simply calls the VisitBulldog method and passes a pointer to the current class. Now we look at our concrete derived visitor classes. First, the class that will change the dog’s age: public class AgeVisitor : BaseVisitor { public AgeVisitor() : base() { } public override void VisitBulldog(CBulldog dog) { dog.MyAge = 5; } } This class that will change his bark. public class BarkVisitor : BaseVisitor { public BarkVisitor() : base() { } public override void VisitBulldog(CBulldog dog) { dog.MyBark = "Yip Yip"; } } As you see, all that the methods do are to act upon the dog object passed to them. You can make them as complex or simple as needed. Our test code for the example: class Program { static void Main(string[] args) { CBulldog Mydog; Mydog = new CBulldog(); Mydog.Bark(); Console.WriteLine(Mydog.MyAge.ToString()); AgeVisitor av; av = new AgeVisitor(); Mydog.TakeVisitor(av); Console.WriteLine(Mydog.MyAge.ToString()); BarkVisitor bv; bv = new BarkVisitor(); Mydog.TakeVisitor(bv); Mydog.Bark(); } } If you watch the output window, you will see that the calls to TakeVisitor change the dog’s information. This pattern can help keep your objects cleaner when there are many different types of visitors you want to use.
The Microsoft .Net Framework is a platform that provides tools and technologies to build Networked Applications, 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).
The Common Language Runtime (CLR) is the runtime environment of the .Net Framework. That executes and manages all running code like a Virtual Machine.
CLR is a core component of Microsoft's .NET initiative. Compilers and tools expose the runtime's functionality and enable you to write code.
The benefit of this is managed execution environment.
Code that you develop with a language compiler that targets the runtime is called managed code, it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.
It is Microsoft's implementation of the Common Language Infrastructure (CLI) standard, which defines an execution environment for program code. The CLR runs a form of bytecode called the Common Intermediate Language (CIL, previously known as MSIL -- Microsoft Intermediate Language).
Developers using the CLR write code in a language such as C# or VB.NET. At compile time, a .NET compiler converts such code into CIL code. At runtime, the CLR's just-in-time compiler converts the CIL code into code native to the operating system. Alternatively, the CIL code can be compiled to native code in a separate step prior to runtime. This speeds up all later runs of the software as the CIL-to-native compilation is no longer necessary.
§Memory Management / Garbage Collection
Memory management is the act of managing computer memory. This involves providing ways to allocate portions of memory to programs at their request, and freeing it for reuse when no longer needed. The management of main memory is critical to the computer system.
Virtual memory systems separate the memory addresses used by a process from actual physical addresses, allowing separation of processes and increasing the effectively available amount of RAM using disk swapping. The quality of the virtual memory manager can have a big impact on overall system performance.
Garbage collection is the automated allocation, and deallocation of computer memory resources for a program. This is generally implemented at the programming language level and is in opposition to manual memory management, the explicit allocation and deallocation of computer memory resources.
Garbage Collection
In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory used by objects that are no longer in use by the application. Garbage collection was invented by John McCarthy around 1959 to solve the problems of manual memory management in Lisp.
Garbage collection is often portrayed as the opposite of manual memory management, which requires the programmer to specify which objects to de allocate and return to the memory system. However, many systems use a combination of the two approaches, and there are other techniques being studied (such as region inference) to solve the same fundamental problem.
The basic principles of garbage collection are
1. Find data objects in a program that cannot be accessed in the future
2. Reclaim the resources used by those objects.
Garbage collection frees the programmer from having to worry about releasing objects that are no longer needed, which can otherwise consume a significant amount of design effort. It also aids programmers in their efforts to make programs more stable, because it prevents several classes of runtime errors.
Many computer languages require garbage collection, either as part of the language specification (e.g., Java, C#, and most scripting languages) or effectively for practical implementation (e.g., formal languages like lambda calculus); these are said to be garbage collected languages. Other languages were designed for use with manual memory management, but have garbage collected implementations available (e.g., C, C++). Some languages, like Ada, Modula-3, and C++/CLI allow both garbage collection and manual memory management to co-exist in the same application by using separate heaps for collected and manually managed objects; others, like D, are garbage collected but allow the user to manually delete objects and also entirely disable garbage collection when speed is required. In any case, it is far easier to implement garbage collection as part of the language's compiler and runtime system, but post hoc GC systems exist, including ones that do not require recompilation. The garbage collector will almost always be closely integrated with the memory allocator.
Benefits
Garbage collection frees the programmer from manually dealing with memory allocation and deallocation. As a result, certain categories of bugs are eliminated or substantially reduced:
* Dangling pointer bugs, which occur when a piece of memory is freed while there are still pointers to it, and one of those pointers is used.
* Double free bugs, which occur when the program attempts to free a region of memory that is already free.
* Certain kinds of memory leaks, in which a program fails to free memory that is no longer referenced by any variable, leading, over time, to memory exhaustion.
Researchers draw a distinction between "physical" and "logical" memory leaks. In a physical memory leak, the last pointer to a region of allocated memory is removed, but the memory is not freed. In a logical memory leak, a region of memory is still referenced by a pointer, but is never actually used. Garbage collectors generally can do nothing about logical memory leaks. Novice programmers sometimes believe that garbage collection makes memory leaks impossible, not realizing that logical leaks are still possible.
In languages that provide dynamic allocation, garbage collection is crucial to memory safety and often to the associated property of type safety. This in turn improves the security of the language by preventing a wide class of security vulnerabilities based on over-writing memory in unexpected ways.
Disadvantages
Typically, garbage collection has four main disadvantages.
* Garbage collection is a process that consumes finite computing resources in deciding what memory is to be freed and when whereas manual memory management consumes only the minimum required. So the penalty for the convenience of not having to perform manual memory management is overhead leading to decreased algorithmic efficiency. Clearly, if memory is manually released the instant it is no longer required, it will always be the most efficient method since it will then be immediately available for re-allocation by some other process and will require zero decisions to be made (thus reducing overall memory requirements and elapse time).
* The point when the garbage is actually collected (removed) can be unpredictable, leading to small delays scattered through a session. This can be prohibitive in real-time environments such as device drivers or transaction processing.
* use of recursion delays automatic memory release of the stack until at least the final call has completed causing increased memory requirements.
* Semantic garbage detection will forever remain an insoluble problem for any automatic process due to the halting problem (see Reachability of an object below)
Memory management systems on multi-tasking operating systems usually deal with the following issues.
Relocation
In systems with virtual memory, programs in memory must be able to reside in different parts of the memory at different times. This is because when the program is swapped back into memory after being swapped out for a while it can not always be placed in the same location. The virtual memory management unit must also deal with concurrency. Memory management in the operating system should therefore be able to relocate programs in memory and handle memory references in the code of the program so that they always point to the right location in memory.
Protection
Processes should not be able to reference the memory for another process without permission. This is called memory protection, and prevents malicious or malfunctioning code in one program from interfering with the operation of other running programs.
Sharing
Even though the memory for different processes is normally protected from each other, different processes sometimes need to be able to share information and therefore access the same part of memory. Shared memory is one of the fastest techniques for Inter-process communication.
Logical organization
Programs are often organized in modules. Some of these modules could be shared between different programs, some are read only and some contain data that can be modified. The memory management is responsible for handling this logical organization that is different from the physical linear address space. One way to arrange this organization is segmentation.sfggehehhe
Physical organization
Memory is usually divided into fast primary storage and slow secondary storage. Memory management in the operating system handles moving information between these two levels of memory.
Memory compaction
The technique of relocating all occupied areas of memory to one end of the memory so as to get one large block of free memory space is called compaction.
Memory can be compacted under the following conditions:
1. as soon as a job terminates.
2. When a new job cannot be loaded into memory due to fragmentation.
3. at fixed time intervals.
§Thread Management
In computer science, a thread of execution results from a fork of a computer program into two or more concurrently running tasks. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process. Multiple threads can exist within the same process and share resources such as memory, while different processes do not share these resources.
On a single processor, multithreading generally occurs by time-division multiplexing (as in multitasking): the processor switches between different threads. This context switching generally happens frequently enough that the user perceives the threads or tasks as running at the same time. On a multiprocessor or multi-core system, the threads or tasks will generally run at the same time, with each processor or core running a particular thread or task. Support for threads in programming languages varies: a number of languages simply do not support having more than one execution context inside the same program executing at the same time. Examples of such languages include Python, and OCaml, because the parallel support of their runtime support is limited by the use of a central lock, called "Global Interpreter Lock" in Python, "master lock" in Ocaml. Other languages may be limited because they use threads that are user threads, which are not visible to the kernel, and thus cannot be scheduled to run concurrently. On the other hand, kernel threads, which are visible to the kernel, can run concurrently.
Many modern operating systems directly support both time-sliced and multiprocessor threading with a process scheduler. The kernel of an operating system allows programmers to manipulate threads via the system call interface. Some implementations are called a kernel thread, whereas a lightweight process (LWP) is a specific type of kernel thread that shares the same state and information.
Programs can have user-space threads when threading with timers, signals, or other methods to interrupt their own execution, performing a sort of ad-hoc time-slicing.
§Exception Handling
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution.
Unlike signals and event handlers that are part of the normal program flow, exceptions are typically used to signal that something went wrong (e.g. a division by zero occurred or a required file was not found). Exceptions are raised or thrown (initiated) by either the hardware or the program itself by using a special command.
Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution.
C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any cleanup process.
If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block.
But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks.
If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.
In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc.
Since there is no exception handling catch block, the execution will get terminated.
By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the Exception class.
In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this purpose. The general form of throwing an exception is as follows.
Standard Exceptions
There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime. System.Exception is the base class for all exceptions in C#. Several exception classes inherit from this class including ApplicationException and SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions that derive directly from System.Exception include IOException, WebException etc.
The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions in our applications.
* System.OutOfMemoryException
* System.NullReferenceException
* Syste.InvalidCastException
* Syste.ArrayTypeMismatchException
* System.IndexOutOfRangeException
* System.ArithmeticException
* System.DevideByZeroException
* System.OverFlowException
Exception Types - There are a number of exception classes provided by C#, all of which inherit from the System.Exception class. Following are some common exception classes.
Exception Class
Cause
SystemException
A failed run-time check;used as a base class for other.
AccessException
Failure to access a type member, such as a method or field.
ArgumentException
An argument to a method was invalid.
ArgumentNullException
A null argument was passed to a method that doesn't accept it.
ArgumentOutOfRangeException
Argument value is out of range.
ArithmeticException
Arithmetic over - or underflow has occurred.
ArrayTypeMismatchException
Attempt to store the wrong type of object in an array.
BadImageFormatException
Image is in the wrong format.
CoreException
Base class for exceptions thrown by the runtime.
DivideByZeroException
An attempt was made to divide by zero.
FormatException
The format of an argument is wrong.
IndexOutOfRangeException
An array index is out of bounds.
InvalidCastExpression
An attempt was made to cast to an invalid class.
InvalidOperationException
A method was called at an invalid time.
MissingMemberException
An invalid version of a DLL was accessed.
NotFiniteNumberException
A number is not valid.
NotSupportedException
Indicates sthat a method is not implemented by a class.
NullReferenceException
Attempt to use an unassigned reference.
OutOfMemoryException
Not enough memory to continue execution.
StackOverflowException
A stack has overflown.
§Security
.NET has its own security mechanism with two general features: Code Access Security (CAS), and validation and verification. Code Access Security is based on evidence that is associated with a specific assembly. Typically the evidence is the source of the assembly (whether it is installed on the local machine or has been downloaded from the intranet or Internet). Code Access Security uses evidence to determine the permissions granted to the code. Other code can demand that calling code is granted a specified permission. The demand causes the CLR to perform a call stack walk: every assembly of each method in the call stack is checked for the required permission; if any assembly is not granted the permission a security exception is thrown.
When an assembly is loaded the CLR performs various tests. Two such tests are validation and verification.During validation the CLR checks that the assembly contains valid metadata and CIL(Common Intermediate Language), and whether the internal tables are correct. Verification is not so exact. The verification mechanism checks to see if the code does anything that is 'unsafe'. The algorithm used is quite conservative; hence occasionally code that is 'safe' does not pass. Unsafe code will only be executed if the assembly has the 'skip verification' permission, which generally means code that is installed on the local machine.
.NET Framework uses appdomains as a mechanism for isolating code running in a process. Appdomains can be created and code loaded into or unloaded from them independent of other appdomains. This helps increase the fault tolerance of the application, as faults or crashes in one appdomain do not affect rest of the application. Appdomains can also be configured independently with different security privileges. This can help increase the security of the application by isolating potentially unsafe code. The developer, however, has to split the application into subdomains; it is not done by the CLR.
oDetail knowledge on CTS (Common Type System)
As .Net Framework is language independent and support over 20 different programming languages, many programmers will write data types in their own programming language.
For example, an integer variable in C# is written as int, whereas in Visual Basic it is written as integer. Therefore in .Net Framework you have single class called System.Int32 to interpret these variables. Similarly, for the ArrayList data type .Net Framework has a common type called System.Collections.ArrayList. In .Net Framework, System.Object is the common base type from where all the other types are derived.
This system is called Common Type System. The types in .NET Framework are the base on which .NET applications, components, and controls are built. Common Type System in .Net Framework defines how data types are going to be declared and managed in runtime. The Common Type System performs the following functions.
• Automatically adapts itself in a framework that enables integration of multiple languages, type safety, and high performance code execution.
• Provides an object-oriented model.
• Standardizes the conventions that all the languages must follow.
• Invokes security checks.
• Encapsulates data structures.
There are two general types of categories in .Net Framework that Common Type System support. They are value types and reference types. Value types contain data and are user-defined or built-in. they are placed in a stack or in order in a structure. Reference types store a reference of the value’s memory address. They are allocated in a heap structure. You can determine the type of a reference by the values of self-describing types. Reference types can be categorized into self-describing types, pointer types, or interface types.
There are many other types that can be defined under Value types and Reference types. In .Net Framework, the System namespace is the root for all the data types. This namespace consists of classes such as Object, Byte, String, and Int32 that represents base data types. These base data types are used by all applications. During runtime a type name can be classified into two: the assembly name and the type’s name within the assembly. The runtime in .Net Framework uses assemblies to find and load types.
oDetail knowledge on JIT
The high level programming languages that need to be compiled require a runtime, so that the architecture on which the language runs is provided with details on how to execute its code. All the programming languages use its corresponding runtime to run the application. For example, to run an application developed using Visual Basic, the computer on which the application will be run must be installed with the Visual Basic runtime. The Visual Basic runtime can run only the applications developed with Visual Basic and not the ones developed with any other programming language like Java.
In the .NET Framework, all the Microsoft .NET languages use a common language runtime, which solves the problem of installing separate runtime for each of the programming languages. Microsoft .NET Common Language Runtime installed on a computer can run any language that is Microsoft .NET compatible.
The main advantage of the .NET Framework is the interoperability between different languages. As all the Microsoft .NET languages share the same common runtime language, they all work well together. For example, you can use an object written in C# from Visual Basic.NET. The same applies for all the other Microsoft .NET languages.
When you compile a Microsoft.NET language, the complier generates code written in the Microsoft Intermediate Language (MSIL). MSIL is a set of instructions that can quickly be translated into native code.
A Microsoft.NET application can be run only after the MSIL code is translated into native machine code. In .NET Framework, the intermediate language is complied "just in time" (JIT) into native code when the application or component is run instead of compiling the application at development time. The Microsoft.NET runtime consists of two JIT compilers. They are standard JIT compiler and the EconoJIT compiler. The EconoJIT compiler compiles faster than the standard JIT compiler, but the code it produces is not as optimized as the code obtained from the standard JIT compiler.
oDetail knowledge on Managed and Unmanaged code
Managed Code
Code that you develop with a language compiler, that is targets the common language runtime, is called managed code. Managed code must supply the metadata necessary for the runtime to provide services such as memory management, cross-language integration, code access security, and automatic lifetime control of objects. All code based on Microsoft intermediate language (MSIL) executes as managed code.
Un-Managed Code
Code that is created without regard for the conventions and requirements of the common language runtime. Unmanaged code executes in the common language runtime environment with minimal services (for example, no garbage collection, limited debugging, and so on).
Programs in any programming language could, in principle, be compiled into either managed or unmanaged code. In practice, however, each programming language is typically compiled into one type. For example, the Java programming language is almost always compiled into managed code, although there are Java compilers that can generate unmanaged code (such as GNU Compiler for Java) likewise for the Python language. By contrast, Microsoft's Visual C++ development environment can produce both managed code (running under the .NET CLR) or unmanaged code, running under the older MFC framework. (Microsoft Foundation Class Library)
There are many historical examples of managed code running on a virtual machine, such as UCSD Pascal utilizing p-code. Java popularized this approach with its Bytecode executed by the Java Virtual Machine. Microsoft uses managed code in its CLR virtual machine in the .NET Framework, or another similar virtual machine.
Definitions for managed code:
1. Code that is executed by the CLR. Managed code provides information (i.e., metadata) to allow the CLR to locate methods encoded in assembly modules, store and retrieve security information, handle exceptions, and walk the program stack. Managed code can access both managed data and unmanaged data. Managed data—Memory that is allocated and released by the CLR using Garbage Collection. Managed data can only be accessed by managed code
2.Code that targets the common language runtime, the foundation of the .NET Framework, is known as managed code; code that does not target the common language runtime is known as unmanaged code. You can think of the runtime as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety in the code. The concept of code management is a fundamental principle of the runtime.
3.Managed code supplies the metadata necessary for the CLR to provide services such as memory management, cross-language integration, code access security, and automatic lifetime control of objects. All code based on IL executes as managed code.
4.Code that executes under the CLI execution environment. Managed code uses the execution environment for memory management, object lifetime, and the basic type-system, among other fundamental services.
oClass Libraries
The .NET Framework class library is a library of classes, interfaces, and value types that are included in the Windows Software Development Kit (SDK). This library provides access to system functionality and is designed to be the foundation on which .NET Framework applications, components, and controls are built.
The .NET Framework includes two main components: the common language runtime and the .NET Framework class library. The .NET Framework class library is a collection of reusable types that are tightly integrated with the common language runtime. The class library is object oriented, easy to use, and accelerates your development. For example, the .NET Framework collection classes implement a set of APIs that you can use to develop your own collection classes. The .NET Framework class library enables you to accomplish a range of common programming tasks such as string manipulation, data collection, database connectivity, and file access. You can also use this library to develop console applications, Windows Forms, ASP.NET applications, XML Web services, and Windows services. A classic example is the Web Forms classes. They simplify form development in ASP.NET development projects.
§Framework Class Libraries (FCL)
The .Net Framework Class Library (FCL) is a huge collection of language-independent and type-safe reusable classes. The .Net Framework Class Libraries (FCL) is arranged into a logical grouping according to their functionality and usability is called Namespaces. In the following sections describes how to .Net Framework manages the code in compile time and run time .
The .Net Framework class library (FCL) provides the core functionality of .Net Framework architecture. 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.
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. The .Net Framework class library (FCL) classes are managed classes that provide access to System Services. The .Net Framework class library (FCL) classes are object oriented and easy to use in program developments. Moreover, third-party components can integrate with the classes in the .NET Framework.
BCL (Base Class Libraries) is a part of FCL and provide the most fundamental functionality, which includes classes in namespaces System, System.CodeDom, System.Collections, System.Diagnostics, System.Globalization, System.IO, System.Resources, System.Text, and System.Text.RegularExpressions.
§Base Class Libraries (BCL)
The Base Class Library (BCL) is a standard library available to all languages using the .NET Framework. .NET includes the BCL in order to encapsulate a large number of common functions, such as file reading and writing, graphic rendering, database interaction, and XML document manipulation, which makes the programmer's job easier. It is much larger in scope than standard libraries for most other languages, including C++, and would be comparable in scope to the standard libraries of Java. The BCL is sometimes incorrectly referred to as the Framework Class Library (FCL), which is a superset including the Microsoft.* namespaces. FCL forms the main set with BCL acting as the subset.
Standardized namespaces
System - String, DateTime, Boolean
System.Diagnostics - event logging, performance counters, tracing, and interaction with system processes.
System.Globalization - Culture-related information, including the language, the country/region
System.IO - read from and write to different streams, such as files or other data streams.
System.Net - used on networks HTTP, FTP, and SMTP, SSL.
System.Reflection -It exposes the API to access the Reflective programming capabilities of CLR.
System.Runtime -manage the runtime behavior of an application or the CLR. writing distributed applications, and serializing objects into binary or SOAP.
System.Security - runtime security system. It provides services such as cryptography.
These are the namespaces that are not standardized as of the ECMA and/or ISO standards, and are specific to Microsoft implementation.
System.CodeDom
System.ComponentModel
System.Configuration
System.Data
System.Deployment
System.DirectoryServices
System.Drawing
System.Management
System.Media
System.Messaging
System.Linq
System.Linq.Expressions
System.Resources
System.ServiceProcess
System.Timers
System.Transactions
oMSIL
Common Language Infrastructure, the bytecode is now officially known as CIL.
Common Intermediate Language (CIL) formerly called Microsoft Intermediate Language or MSIL is the lowest-level human-readable programming language in the Common Language Infrastructure and in the .NET Framework. Languages which target the .NET Framework compile to CIL, which is assembled into bytecode. CIL is an object-oriented assembly language, and is entirely stack-based. It is executed by a virtual machine.
During compilation of .NET programming languages, the source code is translated into CIL code rather than platform or processor-specific object code. CIL is a CPU- and platform-independent instruction set that can be executed in any environment supporting the .NET framework. CIL code is verified for safety during runtime, providing better security and reliability than natively compiled binaries.
Microsoft Intermediate Language (MSIL) is the assembly language output by .NET compilers—C#, VB .NET, etc.
Learning MSIL affords the programer the opportunity to understand things that are normally hidden while working in C# or VB NET. Although we seldom—if ever—need to write programs directly in MSIL, there are difficult cases when it can be both enlightening and useful to examine the MSIL code in ILDasm to see what is happening behind the curtain.
The Intermediate Language Assembler (ilasm) that ships with the .NET Framework SDK allows programmers to view MSIL code in human-readable format. Using this utility, the MSIL code of any .NET executable file—.DLL, .EXE—can be inspected.
The Intermediate Language Disassembler (ildasm) disassembles MSIL code back into assembly language source code; so, it can be viewed or modified.
This is the first release of the .NET Framework, released on 13 February 2002 and available for Windows 98, Me, NT 4.0, 2000, and XP. Mainstream support by Microsoft for this version ended 10 July 2007, and extended support ended 14 July 2009.
.NET Framework 1.1
This is the first major .NET Framework upgrade. It is available on its own as a redistributable package or in a software development kit, and was published on 3 April 2003. It is also part of the second release of Microsoft Visual Studio .NET (released as Visual Studio .NET 2003). This is the first version of the .NET Framework to be included as part of the Windows operating system, shipping with Windows Server 2003. Mainstream support for .NET Framework 1.1 ended on 14 October 2008, and extended support ends on 8 October 2013. Since .NET 1.1 is a component of Windows Server 2003, extended support for .NET 1.1 on Server 2003 will run out with that of the OS - currently 14 July 2015.
Changes in 1.1 on comparison with 1.0
* Built-in support for mobile ASP.NET controls. Previously available as an add-on for .NET Framework, now part of the framework.
* Security changes - enable Windows Forms assemblies to execute in a semi-trusted manner from the Internet, and enable Code Access Security in ASP.NET applications.
* Built-in support for ODBC and Oracle databases. Previously available as an add-on for .NET Framework 1.0, now part of the framework.
* .NET Compact Framework - a version of the .NET Framework for small devices.
* Internet Protocol version 6 (IPv6) support.
* Numerous API changes.
.NET Framework 2.0
Released with Visual Studio 2005, Microsoft SQL Server 2005, and BizTalk 2006.
* The 2.0 Redistributable Package can be downloaded for free from Microsoft, and was published on 22 January 2006.
* It is included as part of Visual Studio 2005 and Microsoft SQL Server 2005.
* Version 2.0 without any Service Pack is the last version with support for Windows 98 and Windows Me. Version 2.0 with Service Pack 2 is the last version with official support for Windows 2000 although there have been some unofficial workarounds published online to use a subset of the functionality from Version 3.5 in Windows 2000. Version 2.0 with Service Pack 2 requires Windows 2000 with SP4 plus KB835732 or KB891861 update, Windows XP with SP2 or later and Windows Installer 3.1 (KB893803-v2).
* It shipped with Windows Server 2003 R2 (not installed by default).
Changes in 2.0 in comparison with 1.1
* Numerous API changes.
* A new hosting API for native applications wishing to host an instance of the .NET runtime. The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more (detailed reference). It was initially developed to efficiently host the runtime in Microsoft SQL Server, which implements its own scheduler and memory manager.
* Full 64-bit support for both the x64 and the IA64 hardware platforms.
* Language support for generics built directly into the .NET CLR.
* Many additional and improved ASP.NET web controls.
* New data controls with declarative data binding.
* New personalization features for ASP.NET, such as support for themes, skins and webparts.
* .NET Micro Framework - a version of the .NET Framework related to the Smart Personal Objects Technology initiative.
* Partial classes
* Anonymous methods
* Data Tables
.NET Framework 3.0
.NET Framework 3.0, formerly called WinFX, was released on 21 November 2006. It includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems. It is also available for Windows XP SP2 and Windows Server 2003 as a download. There are no major architectural changes included with this release; .NET Framework 3.0 uses the Common Language Runtime of .NET Framework 2.0. Unlike the previous major .NET releases there was no .NET Compact Framework release made as a counterpart of this version.
.NET Framework 3.0 consists of four major new components:
* Windows Presentation Foundation (WPF), formerly code-named Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies. See WPF SDK for developer articles and documentation on WPF.
* Windows Communication Foundation (WCF), formerly code-named Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
* Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
* Windows CardSpace, formerly code-named InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website.
.NET Framework 3.5
Version 3.5 of the .NET Framework was released on 19 November 2007, but it is not included with Windows Server 2008. As with .NET Framework 3.0, version 3.5 uses the CLR of version 2.0. In addition, it installs .NET Framework 2.0 SP1, (installs .NET Framework 2.0 SP2 with 3.5 SP1) and .NET Framework 3.0 SP1 (installs .NET Framework 3.0 SP2 with 3.5 SP1), which adds some methods and properties to the BCL classes in version 2.0 which are required for version 3.5 features such as Language Integrated Query (LINQ). These changes do not affect applications written for version 2.0, however.
As with previous versions, a new .NET Compact Framework 3.5 was released in tandem with this update in order to provide support for additional features on Windows Mobile and Windows Embedded CE devices.
The source code of the Base Class Library in this version has been partially released (for debugging reference only) under the Microsoft Reference Source License.
Changes since version 3.0
* New language features in C# 3.0 and VB.NET 9.0 compiler
* Adds support for expression trees and lambda methods
* Extension methods
* Expression trees to represent high-level source code at runtime.
* Anonymous types with static type inference
* Language Integrated Query (LINQ) along with its various providers
o LINQ to Objects
o LINQ to XML
o LINQ to SQL
* Paging support for ADO.NET
* ADO.NET synchronization API to synchronize local caches and server side datastores
* Asynchronous network I/O API.
* Peer-to-peer networking stack, including a managed PNRP resolver.
* Managed wrappers for Windows Management Instrumentation and Active Directory APIs
* Enhanced WCF and WF runtimes, which let WCF work with POX and JSON data, and also expose WF workflows as WCF services. WCF services can be made stateful using the WF persistence model.
* Support for HTTP pipelining and syndication feeds.
* ASP.NET AJAX is included
* New System.CodeDom namespace.
Service Pack 1
The .NET Framework 3.5 Service Pack 1 was released on 11 August 2008. This release adds new functionality and provides performance improvements under certain conditions, especially with WPF where 20-45% improvements are expected. Two new data service components have been added, the ADO.NET Entity Framework and ADO.NET Data Services. Two new assemblies for web development, System.Web.Abstraction and System.Web.Routing, have been added; these are used in the ASP.NET MVC Framework and, reportedly, will be utilized in the future release of ASP.NET Forms applications. Service Pack 1 is included with SQL Server 2008 and Visual Studio 2008 Service Pack 1.
There is also a new variant of the .NET Framework, called the ".NET Framework Client Profile", which at 28 MB is a lot smaller than the full framework and only installs components that are the most relevant to desktop applications. However, the Client Profile amounts to this size only if using the online installer. When using the off-line installer, the download size is still 250 MB.
Changes in 3.5 in comparison with 2.0
·.NET Framework 3.0, version 3.5 uses the CLR of version 2.0.
·Windows Workflow Foundation (WF)
·Windows Communication Foundation (WCF)
·Windows Presentation Foundation (WPF) and Windows CardSpace.
·New assemblies to avoid breaking changes.
·Deep integration of Language Integrated Query (LINQ) and data awareness.
·ASP.NET AJAX lets you create more efficient, more interactive, and highly-personalized Web experiences that work across all the most popular browsers.
·New Web protocol support for building WCF services including AJAX, JSON, REST, POX, RSS, ATOM, and several new WS-* standards.
·Full tooling support in Visual Studio 2008 for WF, WCF, and WPF, including the new workflow-enabled services technology.
·p2p base class
·Active directory
·Anonymous types with static type inference
·Paging support for ADO.NET
·ADO.NET synchronization API to synchronize local caches and server side datastores
·Support for HTTP pipelining and syndication feeds.
·New System.CodeDom namespace.
1) LINQ Support
2) Expression Blend Support
3) Windows Presentation Foundation
4) VS 2008 Multi-Targeting Support
5) AJAX support for ASP.NET
6) JavaScript Debugging Support
7) Nested Master Page Support
8) LINQIntellisense and Javascript Intellisense support for silverlight applications
9) Intellisense Support:
10) Organize Imports or Usings 11) Intellisense Filtering
12) Intellisense Box display position
13) Visual Studio 2008 Split View
14) HTML JavaScript warnings, not as errors
15) Debugging .NET Framework Library Source Code
16)In built Silverlight Library
17) Visual Studio LINQ Designer
18) Inbuilt C++ SDK 19) Microsoft Popfly Support
.NET Framework 4.0
Microsoft announced the .NET Framework 4.0 on 29 September 2008. The Public Beta was released on 20 May 2009. Some focuses of this release are:
* Parallel Extensions to improve support for parallel computing, which target multi-core or distributed systems. To this end, they plan to include technologies like PLINQ (Parallel LINQ), a parallel implementation of the LINQ engine, and Task Parallel Library, which exposes parallel constructs via method calls.
* Visual Basic and C# languages innovations such as statement lambdas, implicit line continuations, dynamic dispatch, named parameters, and optional parameters.
* Full support for IronPython, IronRuby, and F#.
* Support for a subset of the .NET Framework and ASP.NET with the "Server Core" variant of Windows Server 2008 R2.
* Support for Code Contracts.
* Inclusion of the Oslo modelling platform, along with the M programming language.
In conjunction with .NET Framework 4.0, Microsoft will offer a set of enhancements, codenamed Dublin, for Windows Server 2008 application server capabilities. Dublin will extend IIS to be a "standard host" for applications that use either WCF or WF.
To begin programming with C#, you first need to install a C# compiler. You can either use a command line compiler available from Microsoft or third party compiler kit such as the one developed by Mono. Microsoft's C# compiler is widely used by many developers as the Mono compiler kit is not yet fully developed. In addition to this you can also build C# applications with Visual C# .NET. It is a robust development tool used for developing all kinds of C# applications.
Microsoft's C# compiler is available in the form of a package called the .NET Software Development Kit (SDK).Visual Studio .NET comes with .NET Framework SDK.
In addition to Microsoft's C# compiler you also have an option to install Mono C# compiler kit available. Mono is a project started to create .NET compilers meant for platforms other than Windows, such as Linux. But the project is still under development and with each release of the kit more features and additional support for namespaces are added.
The upcoming version of the Mono compiler kit promises to provide support for Windows Forms, ASP.NET and ADO.NET. Moreover, the new compiler will also provide database connectivity support for MySQL databases.
C# compiler generates programs for the .NET framework, not native code.
Broadly speaking, one can compile C# classes into either executable files or dynamic link library - DLL - files. An executable file is one that can contain a runnable program (note that in the classes compiled to an executable file, there should be only one 'Main' method). A .NET dynamic link library just collects together an assembly of classes, which can then be instantiated and utilized by programs in the course of their running.
If your classes reference external classes, the C# compiler must be able to locate them. By default, the compiler only looks within the 'mscorlib.dll' assembly, which supports the basic Common Language Runtime functions. To point the compiler in the direction of other classes, use the switch described in the table below.
The following gives a list of the compiler switches we have found useful, but we would advise you to look further at the .NET documentation to see which other ones are available.
Compiler Switch
Description
/r:dll or /reference:dll
eg.
/r:System.xml.dll, System.Net.dll
This tells the C# compiler to include one or more of the .NET framework DLLs. As the standard library namespaces are not automatically referenced by the compiler, it is necessary to tell it which ones are needed. This switch also allows you to include your own DLLs.
/out: file
eg.
/out:fred.dll
Specifies the filename to which the compiled code is to be written.
/doc: file
eg.
/doc:doc.xml
Requests the production of xml documentation into the specified file (see lesson 19).
/t:type or /target:type
eg.
/t:exe - produce a console executable file (default)
/t:library - produce a dll file
/t:module - creates each file into its own dll, eg. fred.cs will be converted to fred.dll
/t:winexe - produce a windows executable file
This is used to specify the type of output file produced
If you are regularly compiling a program and using a lot of switches in your program, we have found it useful to put the compile command in a batch file rather than writing out the entire command each time.
oData Types
Data are pieces of information that represent the qualitative or quantitative attributes of a variable or set of variables.
Almost all programming languages explicitly include the notion of data type, though different languages may use different terminology. Most programming languages also allow the programmer to define additional data types, usually by combining multiple elements of other types and defining the valid operations of the new data type. For example, a programmer might create a new data type named "Person" that specifies that data interpreted as Person would include a name and a date of birth. Common data types may include (integer, decimal, string, floating-point)
A data type also represents a constraint placed upon the interpretation of data in a type system, describing representation, interpretation and structure of values or objects stored in computer memory. The type system uses data type information to check correctness of computer programs that access or manipulate the data.
EX:
Abstract data types (store, fetch)
Algebraic data types
Composite data types
Function types
Machine data types (bit - machine code)
Object types
Pointer and reference data types
Primitive data types
C# is a "Strongly Typed" language. Thus all operations on variables are performed with consideration of what the variable's "Type" is. There are rules that define what operations are legal in order to maintain the integrity of the data you put in a variable.
Data is physically stored inside cells of memory. This memory could be physical memory (Hard disk) or logical memory (RAM). Any cell of memory is represented with a unique address. This address is more than some combination of numbers or symbols.
C# language provides for practically all the data types. These types can be divided in three categories: value types, reference types and pointer types.
There are some more basic concepts to be learnt before the discussion of the data types. This is about variables and constants. A Variable is a named cell of memory used for data storage. A Variable value can be changed anytime. Every variable must have a type and this type must be set before it is used. Qualifying a variable with a type is called as declaration of variable. The type of a variable is the most important aspect and it defines the behavior of variable. All variables can be divided into seven main categories depending on the context of usage:
In object-oriented programming, a value type is a data type that can exist outside dynamic memory allocation. Unlike reference types, value types can be directly embedded into composite objects.
Primitive types are always value types.
Value types can exist in dynamically allocated memory, such as embedded into a dynamic object. Some platforms also allow direct dynamic allocation of value objects, while others require the value to be copied into a specific dynamic object. The later process is called boxing.
On some platforms, a value may be directly linked to by a pointer or reference. On others, it is a prerogative of reference types.
Value types represent primitive values such as integers or floating-point values. There are three general categories of value types: enumerations, which are described in detail in Chapter 10; built-in value types; and user-defined value types, or structs. As we have seen, value types store their data directly on the stack. Since parameters are by default passed by value in C#, when a value-type parameter is passed into a method, a new copy of the value is created; any changes made to the parameter won't result in changes to the variable passed into the method. Method parameters are discussed in detail in Chapter 12.
Main Features of Value Types
A variable of a value type always contains a value of that type. The assignment to a variable of a value type creates a copy of the assigned value, while the assignment to a variable of a reference type creates a copy of the reference but not of the referenced object.
All value types are derived implicitly from the Object class.
Unlike reference types, it is not possible to derive a new type from a value type. However, like reference types, structs can implement interfaces.
Unlike reference types, it is not possible for a value type to contain the null value.
Each value type has an implicit default constructor that initializes the default value of that type. For information on default values of value types, see Default Values Table.
Initializing Value Types
Local variables in C# must be initialized before being used. Therefore, if you declare a local variable without initialization like this:
int myInt;
you cannot use it before you initialize it. You can initialize it using the following statement:
myInt = new int(); // Using the new operator calls the default constructor of the specific type and assigns the default value to the variable.
myInt = 0;
·Predefined Value Types
The .NET Framework provides a number of predefined value types. These represent various integer, floating point, character, and Boolean values. In other programming languages these are often referred to as primitive data types. The built-in data types of the .NET Framework are defined as structures and can be found in the System namespace. A list of the built-in value types available in C# is given below:
EX: Boolean, Byte, Char, Decimal, Double, Int 16/32/64,
C# provides a set of predefined types, most of which will be familiar to C and C++ developers.
The predefined reference types are object and string. The type object is the ultimate base type of all other types. The type string is used to represent Unicode string values. Values of type string are immutable.
The predefined value types include signed and unsigned integral types, floating-point types, and the types bool, char, and decimal. The signed integral types are sbyte, short, int, and long; the unsigned integral types are byte, ushort, uint, and ulong; and the floating-point types are float and double.
The bool type is used to represent Boolean values: values that are either true or false. The inclusion of bool makes it easier to write self-documenting code; it also helps eliminate the all-too-common C++ coding error in which a developer mistakenly uses "=" when "==" should have been used.
·Nullable Types
So .Net Framework 2.0 comes out with a great new feature and solution to your problem. It is The Nullable Value Types. I'm saying .Net Framework to generalize the feature as it is a new feature in both C# and VB.NET.
In .Net Framework 2.0, value types can be extended to take either their normal values or a null value. Such an extension is called a nullable type.Nullable type is constructed from the generic Nullable structure. By having this feature, you can submit null values to you database table field normally, like submitting a null DateTime value to a datetime field in your database table.
Nullable types are instances of the System.Nullable struct.
Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)
An instance of the Nullable type has two public properties.
* HasValue - A Boolean property denoting the validity of the value contained in the object.
* Value - A value contained in the object.
The 'true' value for the HasValue property guarantees the validity of the value contained in the object which can be accessed through the Value property. A 'false' value for the HasValue indicates the invalid value contained by the object suggesting not to use the Value property.
An instance for which HasValue is false is said to be null. A null instance has an undefined value. Attempting to read the Value of a null instance causes a System.InvalidOperationException to be thrown.
Taking about the default values for the Nullable type we can say; Any instance of a Nullable type is said to have a default value when the HasValue is set to 'false' and the value property is undefined. This value is known as an null value of an Nullable type. While implicitly converting the 'null' value to any nullable type values the conversion results in the null value of the nullable type.
Simply like this:
C#
DataTime? dtmVarName = null;
int? intVarName = null;
bool? bVarName = null;
VB.NET
Dim dtmVarName As Nullable(Of DateTime)
Dim intVarName As Nullable(Of Integer)
Dim bVarName As Nullable(Of Boolean
§Reference Types
In programming language theory, a reference type is a data type that can only be accessed by references. Unlike objects of value types, objects of reference types cannot be directly embedded into composite objects and are always dynamically allocated. They are usually destroyed automatically after they become unreachable.
For immutable objects, the distinction between reference type to an immutable object type and value type is sometimes unclear, because a reference type variable to an immutable object behaves with the same semantics as a value type variable—for example, in both cases the "value" of the data the variable represents can only be changed by direct assignment to the variable (whereas for mutable objects, the data could be changed by modifying the object through another reference to the object).
Reference types store a reference to the value’s memory address and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. The data type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates.
The .NET Framework includes a variety of reference types; this includes the String object, along with all arrays (even if their elements are value types), class types, and delegates. You can think of a reference type as anything that inherits from the Object class; this means that every object you create is a reference type.
One way to identify a reference type is by using a new keyword that isn’t used for value types. The following C# snippet shows the creation of a StringBuilder object, which is a reference type.
StringBuilder sb = new StringBuilder();
When the runtime deals with reference types, it allocates two spaces in memory: one for the actual object (StringBuilder in the previous example) and one for its reference (sb in the previous example). The actual object is stored on the managed heap, so it is within the reach of the garbage collector. The dispose method is used to release its memory and make it available to the garbage collector.
On the other hand, the reference to the object is stored on the stack. When using reference types, the ref keyword is used in both the method signature and when it is called in C# to tell the system that you are working with a reference to the object. In VB.NET, ByRef is used in the method signature with nothing when the method is called.
A user-defined type (UDT) is a named data type that is created in the database by the user. A UDT can be a distinct type which shares a common representation with a built-in data type or a structured type which has a sequence of named attributes that each has a type.
There are three types of user-defined data type:
* Distinct type
* Structured type
* Reference type
Distinct types
A distinct type is a user-defined data type that shares its internal representation with an existing type (its "source" type), but is considered to be a separate and incompatible type for most operations. For example, one might want to define a picture type, a text type, and an audio type, all of which have quite different semantics, but which use the built-in data type BLOB for their internal representation.
Structured types
A structured type is a user-defined data type that has a structure that is defined in the database. It contains a sequence of named attributes, each of which has a data type. A structured type also includes a set of method specifications.
Reference types
A reference type is a companion type to a structured type. Similar to a distinct type, a reference type is a scalar type that shares a common representation with one of the built-in data types. This same representation is shared for all types in the type hierarchy. The reference type representation is defined when the root type of a type hierarchy is created. When using a reference type, a structured type is specified as a parameter of the type. This parameter is called the target type of the reference.
Anonymous types are new in C# 3.0 and VB 9.0 (Visual Studio 2008). An anonymous type allows you to encapsulate a set of properties (not methods) into a specific object without explicitly defining a type. Anonymous types are a convenient language feature of C# and VB that enable developers to concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.
Anonymous types are particularly useful when querying and transforming/projecting/shaping data with LINQ.
When you create a class, such as a Customer class, you are explicitly creating a Customer type with defined properties and methods. The resulting class defines a Customer type which is a named type with the name Customer.
There are times, however, where you need a temporary type. You could explicitly create this type using a class, but that seems like overkill if you only plan to use the type within one routine. This is where an anonymous type is very useful.
It is important to note that the properties of an anonymous type are read/write in VB, but read-only in C#.
var stats = new {Name = String.Empty, Max = 0,
Min = 0, Ave = 0};
§Type Conversion
Conversion is the process of changing a value from one type to another. Conversions may either be widening or narrowing.
Widening conversions: When a particular data type is converted to a data type that is capable of storing more data than the source data type is referred to as widening conversion. The simple examples of widening conversion can be Numeric type conversions in the direction Byte, Short, Integer, Long, Decimal, Single, Double, here every type listed to the right of a type is capable of storing more data than its left listed type. If we takes the case of reference data types then Conversions from any derived type to one of its base types is also referred to as widening conversion. Widening conversion never cause overflow.
Narrowing conversions: A narrowing conversion occurs when a variable is converted to a type that is not capable of storing the data held by the source data type variable. These conversions are known to possibly lose information and conversions across domains of types sufficiently different to merit narrowing notation. These means narrowing conversions entail loss of information and may fail.
Reference conversions: These are conversion from one reference type to another. Reference conversions, implicit or explicit, never change the referential identity of the object being converted. In other words, while a reference conversion may change the type of the reference, it never changes the type or value of the object being referred to.
Boxing and Un-boxing conversions: A boxing conversion permits any value-type to be converted to the type object or to any interface-type implemented by the value-type. Boxing a value of a value-type consists of allocating an object instance and copying the value-type value into that instance. Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:
Interface conversion: Converting an interface to a value type consists of copying the value in the interface instance to the target variable (which may be a temporary).
Conversion operators:
C# allows the pre-defined implicit and explicit conversions to be augmented by user-defined conversions. User-defined conversions are introduced by declaring conversion operators in class and struct types.
Implicit conversion: The implicit keyword is used to declare an implicit user-defined type conversion operator.
SomeType x;
int i = x; // implicitly call SomeType's implicit conversion function that returns int value.
Explicit Conversions: Explicit conversion is performed using casting. Casting occurs when you prefix a conversion with a data type that defines the type of the conversion you want to perform. The explicit keyword is used to declare an explicit user-defined type conversion operator. The set of explicit conversions includes all implicit conversions. Example:
int i;
SomeType x = (SomeType)i;
oFlow Control
That is, execution began at the first line of code and progressed through line-by-line until the end of the example was reached. In the real world, this type of program is very rare for anything except the most basic tasks. For complex software program flow control statements are a necessity.
Program flow control statements can be divided into four categories
* Loops. Loops allow a defined section of code to be executed multiple times until a condition is met. A loop structure is the main focus of this article.
* Conditional Processing. Conditional processing statements and structures permit code to be executed only when certain defined conditions are met. These statements will be the topic for a later article in the tutorial.
* Jumps. Jump statements are simple commands that can be used to immediately transfer the control of a program to another statement. The break and continue jump statements are described in this article. The infamous goto statement will be considered later.
* Exception Handling. When exceptions occur, rather than simply presenting the user with an error and stopping execution of the program, they should be handled. Exception handling statements provide this capability and will be described in a later article in this tutorial.
oLooping
Ability to repeat a block of code X times. C# provides a number of the common loop statements:
·while
·do-while
·for
·foreach
oOperators
Operators are symbols and notations used in a programming language to express a certain statement. For example if we want to add two variables, we would use the "+" operator.
C# has a large number of operators, some will be used in every single program or module, while others you may not ever use.
The most common of the operators are the arithmetic and logic operators.
C# preprocessor is fundamentally very similar to C preprocessor and the whole concept in C# has been taken from C language specification.
The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.
But in C# only concept has been taken from C. But the C# compiler does not have a separate preprocessor, the directives described in this C# are processed as if there was one. Unlike C and C++ directives, you cannot use these directives to create macros.
A preprocessor directive must be the only instruction on a line. Preprocessing directives are lines in your program that start with `#'. Whitespace is allowed before and after the `#'. The `#' is followed by an identifier that is the directive name. For example, `#define' is the directive The C# language's preprocessor directives are as follows:
1.Conditional compilation. Using special preprocessing directives, you can include or exclude parts of the program according to various conditions.
2.Line control. If you use a program to combine or rearrange source files into an intermediate file, which is then compiled, you can use line control to inform the compiler of where each source line originally came from.
3.Error and Warning reporting. The directive `#error' causes the preprocessor to report a fatal error and the directive `#warning' is like the directive `#error', but causes the preprocessor to issue a warning and continue preprocessing.
·Classes and Objects
C# .NET is an Object Oriented programming language. Objects are created from Classes, which you've already used a lot. The Windows Form itself is a Class, and when you run your programme, you are creating Objects: a Form object, a button object, a Textbox object, etc. In this section, you'll learn how to write your own Classes, and turn them in to Objects
oClasses
A Class is simply a chuck of code that does a particular job. The idea is that you can reuse this code (Class) whenever you need it, or when you need it in other projects. It saves you from having to write the same thing over and over again.
oObjects
You do all the coding in a Class (recipe), and then instruct C# to make an object (a Banana Cake). The two processes are different. But all you are really doing with Classes and Objects is trying to separate code into chunks, so that it can be reused. When the code is being used, it's an object. But the object is created from your code (Class).
§Defining a Class
A Class is simply a chuck of code that does a particular job. The idea is that you can reuse this code (Class) whenever you need it, or when you need it in other projects. It saves you from having to write the same thing over and over again.
Partial classes mean that your class definition can be split into multiple physical files.
Logically, partial classes do not make any difference to the compiler. During compile time, it simply groups all the various partial classes and treats them as a single entity.
One of the greatest benefits of partial classes is that it allows a clean separation of business logic and the user interface (in particular the code that is generated by the visual designer). Using partial classes, the UI code can be hidden from the developer, who usually has no need to access it anyway. Partial classes will also make debugging easier, as the code is partitioned into separate files.
The C# 3.0 specifications describe anonymous types as tuple types automatically inferred and created from object initializers. Before you can fully understand the meaning of this definition, you need to understand the term "object initializer," which is the basis of the anonymous types feature. That allows data types to encapsulate a set of properties into a single object without having to first explicitly define a type.
This is an important feature for the SQL-like Language Integrated Query (LINQ) feature that is integrated into C# and VB.net. Since anonymous types do not have a named typing, they must be stored in variables declared using the var keyword, telling the C# compiler to use type inference for the variable. The properties created are read-only in C#, however they are read-write in VB.net.
var Customer = new
{
Company = "West Wind",
Name = "Rick",
Entered = DateTime.Now,
BillRate = 150M,
Contacts = new
{
Phone = "808 121-1211",
Fax = "808 231-1211",
Email = "rick@west-wind.com"
}
};
List listOfCustomers =
new List {
{ Id = 1, Name="Dave", City="Sarasota" },
{ Id = 2, Name="John", City="Tampa" },
{ Id = 3, Name="Abe", City="Miami" }
};
This code creates a new instance of an anonymous type - in this case a simple object instance that holds customer data. Once you have declared the type like the above you can then use the type as if there was a full type declaration, so you can access Customer.Company, Customer.BillRate and so forth.
Visual Studio 2008 is also smart enough to figure out the anonymous type for you so when you're in the editor typing away you get Intellisense when you type Customer.:
§Instance Members
Instance members belong to the object that they are instantiated from. While this may sound somewhat cryptic, it will all become much clearer with the following code:
publicclass GenerateClones
{
publicvoid main()
{
//Instantiate our class and create a clone
CloneGenerator c1 = new CloneGenerator("Bob");
CloneGenerator c2 = new CloneGenerator("Jon");
CloneGenerator c3 = new CloneGenerator("Jim");
//this string will contain the name Bob
string clone1 = c1.getName();
//this string will contain the name Jon
string clone2 = c2.getName();
//this string will contain the name Jim
string clone3 = c3.getName();
//Call the Static function
//iCloneCount will hold the value of 3 after this assignment
int iCloneCount = CloneGenerator.countClones();
}
}
Static members are not associated with a specific instance of a class. To call a static member, you qualify the static member with the class name. Because static members are not associated with object instances, they do not have access to non-static members
For example, MyClass.StatMember
Because static members are not associated with object instances, they do not have access to non-static members.
Non-static members are called instance members because they are associated with individual object instances. Think of static members as belonging to the class and instance members belonging to instances of the class (that is, objects).
§Static Members
Static members are not associated with a specific instance of a class. To call a static member, you qualify the static member with the class name. Because static members are not associated with object instances, they do not have access to non-static members
For example, MyClass.StatMember
Because static members are not associated with object instances, they do not have access to non-static members.
Access Modifiers (Access Specifiers) describes as the scope of accessibility of an Object and its members. All C# types and type members have an accessibility level. We can control the scope of the member object of a class using access specifiers. We are using access modifiers for providing security of our applications. When we specify the accessibility of a type or member we have to declare it by using any of the access modifiers provided by CSharp language.
public: public is the most common access specifier in C# . It can be access from anywhere that means there is no restriction on accessibility. The scope of the accessibility is inside class as well as outside. The type or member can be accessed by any other code in the same assembly or another assembly that references it. private : The scope of the accessibility is limited only inside the classes or struct in which they are declared. The private members cannot be accessed outside the class and it is the least permissive access level. protected : The scope of accessibility is limited within the class or struct and the class derived (Inherited )from this class. Internal : The internal access modifiers can access within the program that contain its declarations and also access within the same assembly level but not from another assembly. protected internal : Protected internal is the same access levels of both protected and internal. It can access anywhere in the same assembly and in the same class also the classes inherited from the same class.
Function members are members that contain executable statements. Function members are always members of types and cannot be members of namespaces. C# defines the following categories of function members:
Method is object-oriented item of any language. All C# programs are constructed from a number of classes and almost all the classes will contain methods. A class when instantiated is called an object. Object-oriented concepts of programming say that the data members of each object represent its state and methods represent the object behavior.
EX: Return-type methodname ( Parameterslist );
The input parameters can be passed in two ways.
* Value type
public int CalculateBirthYear(int year)
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
return b;
}
* Reference type.
public int CalculateBirthYear(ref int year)
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
return b;
}
othis keyword
The "this" keyword gets you an access to an instance of the class, and you can use it with instance methods, instance constructors and instance properties. You can't use it with any static members; this makes sense because a static member works on the class itself, not on an instance of it. Use the "this" keyword followed by the (.) operator to get access to the class members on an instance object. Take a look at the following class:
using System;
namespace Company
{
public class Employee
{
public string FirstName;
public string LastName;
Properties are used to get or set the value of data members of a class.
They are used to implement data security.
A property contains two blocks: (i) get and (ii) set. These blocks works on the basis of calling conventions.
get and set block is implicit calling of grammar language. Property is define public normally to have get and set control.
For each data members we have to create one property.
In c-sharp we create indexers in place of parameterized property. (In VB you can have parameterized property).
For static data member static properties are used.
Difference between Property and Methods
Property
Property is implicitly called using calling convention
Property works on compile and runtime.
Method
Method is explicitly called
Methods works on runtime.
If you define a property with only a get accessor, that property will be read-only. Likewise, if you define a property with only a set accessor, you’ll end up with a write-only property. And lastly, a property with both accessors is a read-write property.
·Partial Methods
C# 3.0, we can now have partial method. Partial methods are the code block which reside inside a partial type and gets executed only when it has definition. This gives us the extensibility and if user wants to implement the rule, they can go ahead and define the body but if they do not want it will not. This improves the performance as you are not loading/creating unwanted methods.
publicpartialclassMyClass
{
//Public Constructor
public MyClass(int iInput)
{
//Calling Partial Method
GetMessage(iInput);
}
//Public Property
publicstring Messgae { get; set; }
//Partial Method
partialvoid GetMessage(int iVal);
}
In the partial method declaration I cannot have any body. So, where we need to define the body of our method?
Should be in another partial. But since there is no body, the method actually will have no existence in IL.
Ø A partial method must be declared within a partial class or partial struct
Ø A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers
Ø Partial methods must have a void return type
Ø A partial method cannot have out parameters
Ø Definition has to end with “;” No {} is allowed in this scope.
# Can be marked static or unsafe.
# Can be generic.
# Can have ref but not out parameters.
# Cannot be referenced as a delegate until they are implemented
# Cannot have access modifiers such as public, private or internal.
Constructor is a special kind of method of a class, which gets executed when its (class) object is created.
What is constructor?
Constructor is used to initialize an object (instance) of a class.
Constructor is a like a method without any return type.
Constructor has same name as class name.
Constructor follows the access scope (Can be private, protected, public, Internal and external).
Constructor can be overloaded.
Constructors generally following types :
Default Constructor
Parameterized constructor
Private Constructor
Static Constructor
Copy Constructor
Default Constructor A constructor that takes no parameters is called a default constructor.
When a class is initiated default constructor is called which provides default values to different data members of the class.
Parameterized constructor Constructor that accepts arguments is known as parameterized constructor. There may be situations, where it is necessary to initialize various data members of different objects with different values when they are created. Parameterized constructors help in doing that task.
Private Constructor Private Constructors are used to restrict the instantiation of object using 'new' operator. A private constructor is a special instance constructor. It is commonly used in classes that contain static members only.
This type of constructors is mainly used for creating singleton object.
If you don't want the class to be inherited we declare its constructor private.
We can't initialize the class outside the class or the instance of class can't be created outside if its constructor is declared private.
Static Constructors C# supports two types of constructor, a class constructor static constructor and an instance constructor (non-static constructor).
Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize them in the same way it can optimize inline assignments. Non-static constructors are inline and are faster.
Static constructors are used to initializing class static data members.
Point to be remembered while creating static constructor:
1. There can be only one static constructor in the class.
2. The static constructor should be without parameters.
3. It can only access the static members of the class.
4. There should be no access modifier in static constructor definition.
Static members are preloaded in the memory. While instance members are post loaded into memory.
Static methods can only use static data members.
Copy Constructor If you create a new object and want to copy the values from an existing object, you use copy constructor.
This constructor takes a single argument: a reference to the object to be copied.
·Constructor Chaining
Constructor chaining occurs through the use of inheritance. A subclass constructor method's first task is to call its superclass' constructor method. This ensures that the creation of the subclass object starts with the initialization of the classes above it in the inheritance chain.
There could be any number of classes in an inheritance chain. Every constructor method will call up the chain until the class at the top has been reached and initialized. Then each subsequent class below is initialized as the chain winds back down to the original subclass. This process is called constructor chaining.
Another approach is to use constructor chaining, where a constructor calls another constructor in its class using the ": this()" designation as shown below:
public Test( bool a, int b, string c ): this( a, b )
{
this.m_C = c;
}
public Test( bool a, int b, float d ): this( a, b )
{
this.m_D = d;
}
private Test( bool a, int b )
{
this.m_A = a;
this.m_B = b;
}
§Destructors
The .NET framework has an in built mechanism called Garbage Collection to de-allocate memory occupied by the un-used objects. The destructor implements the statements to be executed during the garbage collection process. A destructor is a function with the same name as the name of the class but starting with the character ~.
Remember that a destructor can't have any modifiers like private, public etc. If we declare a destructor with a modifier, the compiler will show an error.Also destructor will come in only one form, without any arguments. There is no parameterized destructor in C#.
Destructors are invoked automatically and can't be invoked explicitly. An object becomes eligible for garbage collection, when it is no longer used by the active part of the program. Execution of destructor may occur at any time after the instance or object becomes eligible for destruction.
Example:
class Complex
{
public Complex()
{
// constructor
}
~Complex()
{
// Destructor
}
}
We use static class when there is no data or behavior in the class that depends on object identity. A static class can have only static members. We cannot create instances of a static class using the new keyword. .NET Framework common language runtime (CLR) loads Static classes automatically when the program or namespace containing the class is loaded.
Features
Static classes only contain static members.
Static classes cannot be instantiated. They cannot contain Instance Constructors
Static classes are sealed.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state.
static class CompanyInfo
{
public static string GetCompanyName() { return "CompanyName"; }
public static string GetCompanyAddress() { return "CompanyAddress"; }
The Object class, held in the System namespace, is the base class for all classes and data types, including the value types. It is the class at the root of the .NET framework class library's entire type hierarchy.
System.Object defines several public and protected methods that, due to inheritance, are automatically made available to all .NET classes, structures and types, including any classes or structures that you create yourself. If you create a class with no base class specified, it will implicitly derive functionality from Object.
§Testing For Equality
§Implementing Equals
§ToString() Method
ToString returns a human-readable string that is culture-sensitive. For example, for an instance of the Double class whose value is zero, the implementation of Double.ToString might return "0.00" or "0,00" depending on the current UI culture. Here I compare ToString() with no parameters (no format string) and ToString() with the NumberFormatInfo specified. ToString() can receive a System.Globalization. NumberFormatInfo parameter.
Attributes are elements that allow you to add declarative information to your programs. This declarative information is used for various purposes during runtime and can be used at design time by application development tools. For example, there are attributes such as DllImportAttribute that allow a program to communicate with the Win32 libraries. Another attribute, ObsoleteAttribute, causes a compile-time warning to appear, letting the developer know that a method should no longer be used. When building Windows forms applications, there are several attributes that allow visual components to be drag-n-dropped onto a visual form builder and have their information appear in the properties grid. Attributes are also used extensively in securing .NET assemblies, forcing calling code to be evaluated against pre-defined security constraints. These are just a few descriptions of how attributes are used in C# programs.
.net allows the use of custom attributes. Custom Attributes can be used to store information that can be stored at compile time and retrieved at run time. This information can be related to any aspect/feature of target element depending upon the design of application. We will develop a custom attribute ClassInfoAttribute, which will be used for storing information, related to source code. CodeInfoAttribute will have the following information.
Structures (keyword struct) are light-weight objects. They are mostly used when only a data container is required for a collection of value type variables. Structs are similar to classes in that they can have constructors, methods, and even implement interfaces, but there are important differences.
* Structs are value types while classes are reference types, which means they behave differently when passed into methods as parameters.
* Structs cannot support inheritance. While structs may appear to be limited with their use, they require less memory and can be less expensive if used in the proper way.
* Structs always have a default constructor, even if you don't want one. Classes allow you to hide the constructor away by using the "private" modifier, whereas structures must have one.
An Interface is a reference type and it contains only abstract members. Interface's members can be Events, Methods, Properties and Indexers. But the interface contains only declaration for its members. Any implementation must be placed in class that realizes them. The interface can't contain constants, data fields, constructors, destructors and static members. All the member declarations inside interface are implicitly public.
Why use Interface?
1. To allow a class to inherit multiple behaviors from multiple interfaces.
2. To avoid name ambiguity between the methods of the different classes as was in the use of multiple inheritances in C++.
3. To combine two or more interfaces such that a class need only implement the combined result. The example code for this is provided as a source file to be downloaded.
4. To allow Name hiding. Name hiding is the ability to hide an inherited member name from any code outside the derived class.
oDefining an Interface
Interface INode
{
String Text{get;set;}
Object Tag{get;set;}
}
oImplementing an Interface
using System;
namespace PavelTsekov
{
interface I1
{
void MyFunction();
}
interface I2
{
void MyFunction();
}
class Test : I1,I2
{
void I1.MyFunction()
{
Console.WriteLine("Now I can say this here is I1 implemented!");
}
void I2.MyFunction()
{
Console.WriteLine("Now I can say this here is I2 implemented!");
Using the as operator is a better coding strategy than a straight cast because it yields a null on a conversion failure rather than raising an exception.
The first line of code below is a straight cast. This is acceptable practice if you are absolutely certain the object in question implements both interfaces; if the object does not implement the interface you are attempting to get a handle to, .NET will throw an exception. A safer model to use is the as operator, which returns a null if the object cannot return a reference to the desired interface.
IGeometry geometry = point; // straight cast
IGeometry geometry = point as IGeometry; // as operator
oThe is and as operators
The is Operator
You can handle incompatible types by catching InvalidCastException, but there are other ways of handling this problem, such as the is operator. The is operator allows you to determine whether an object reference can be converted into a reference to a given class.
You can use the is operator to test the type of the object without performing a conversion. The is operator returns true if the value on the left is not null and a cast to the class on the right, if performed, would complete without throwing an exception. Otherwise, is returns false.
if (a is Bird)
b = (Bird) a; // Safe, because "a is Bird" returns true
else
Console.WriteLine("Not a Bird");
The as Operator
You can use the as operator to perform conversions between types without raising an exception.
The following statement performs a conversion of the reference in a to a value that references a class of type Bird, and the runtime automatically checks to ensure that the conversion is acceptable.
b = a as Bird;
The as operator differs from the cast operator in the way it handles errors. If, in the preceding example, the reference in variable a cannot be converted in a reference to an object of class Bird, the value null is stored in b, and the program continues. The as operator never raises an exception.
You can rewrite the previous code as follows to display an error message if the conversion cannot be performed:
It allows a class to be defined which has a number of characteristics and then other classes to be created which are derived from that class. The derived class inherits all of the features of the parent class and typically then adds some features of its own.
By deriving classes we create what is often referred to as a class hierarchy. The class at the top of the hierarchy is known as the base class and the derived classes as subclasses. Any number of classes may be derived from a class. It is only possible for a derived class to inherit from one class. As such, C# is known as a single inheritance programming language.
C# supports two types of Inheritance mechanisms
1) Implementation Inheritance
2) Interface Inheritance
oUnderstanding Inheritance in C#
oImplementation inheritance
When a class (type) is derived from another class(type) such that it inherits all the members of the base type it is Implementation Inheritance
oInterface inheritance
When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance
In general Classes can be derived from another class, hence support Implementation inheritance At the same time Classes can also be derived from one or more interfaces Hence they support Interface inheritance Structs can derive from one more interface, hence support Interface Inheritance Structs cannot be derived from another class they are always derived from SystemValueType
C# does not support multiple inheritances, but a class has the option of implementing one or more interfaces. One challenge with interfaces is that they may include methods that have the same signatures as existing class members or members of other interfaces. Explicit interface implementations can be used to disambiguate class and interface methods that would otherwise conflict. Explicit interfaces can also be used to hide the details of an interface that the class developer considers private.
Inheritance is specific to object-oriented programming, where a new class is created from an existing class. Inheritance (often referred to as subclasses) comes from the fact that the subclass (the newly created class) contains the attributes and methods of the parent class. The main advantage of inheritance is the ability to define new attributes and new methods for the subclass which are then applied to the inherited attributes and methods.
This can be used to create a highly specialized hierarchical class structure. The biggest advantage is that there is no need to start from scratch when wanting to specialize an existing class. As a result, class libraries can be purchased; providing a base that can then be specialized at will (the company selling these classes tends to protect member data using encapsulation).
1) single inheritance
public class A
{
}
public class B:A
{
}
2)multiple inheritance
public class A
{
}
public class B
{
}
public class C:A,B
{
}
3)multilevel inheritance
public class A
{
}
public class B:A
{
}
public class C:B
{
}
4)hierarchial inheritance
oUnderstanding Inheritance in C#
C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multiple interface inheritance.
oImplementation inheritance
ChildClass has exactly the same capabilities as ParentClass. Because of this, you can also say ChildClass "is" a ParentClass. This is shown in the Main() method of ChildClass when the print() method is called. ChildClass does not have its own print() method, so it uses the ParentClass print() method. You can see the results in the 3rd line of output.
Base classes are automatically instantiated before derived classes. The ParentClass constructor executed before the ChildClass constructor.
using System;
publicclass Parent
{
string parentString;
public Parent()
{
Console.WriteLine("Parent Constructor.");
}
public Parent(string myString)
{
parentString = myString;
Console.WriteLine(parentString);
}
publicvoid print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class Child : Parent
{
public Child() : base("From Derived")
{
Console.WriteLine("Child Constructor.");
}
publicnewvoid print()
{
base.print();
Console.WriteLine("I'm a Child Class.");
}
publicstaticvoid Main()
{
Child child = new Child();
child.print();
((Parent)child).print();
}
}
Output:
From Derived
Child Constructor.
I'm a Parent Class.
I'm a Child Class.
I'm a Parent Class.
Interface inheritance is the process of defining a new interface with all the methods found in one or more old interfaces. Unlike Object Oriented Inheritance, where all the methods (there implementations) and attributes of a base class are found in the derived class, interface inheritance only specifies that the names of the methods and attributes in the base interface is found in the derived interface. Like inheritance diagrams which describe model inheritance, lattice graphs are used to model interface inheritance.
A delegate is a C# language element that allows you to reference a method. If you were a C or C++ programmer, this would sound familiar because a delegate is basically a function pointer. However, developers who have used other languages are probably wondering, "Why do I need a reference to a method?”
using System;
// this is the delegate declaration
public delegate int Comparer(object obj1, object obj2);
public class Name
{
public string FirstName = null;
public string LastName = null;
public Name(string first, string last)
{
FirstName = first;
LastName = last;
}
// this is the delegate method handler
public static int CompareFirstNames(object name1, object name2)
{
string n1 = ((Name)name1).FirstName;
string n2 = ((Name)name2).FirstName;
if (String.Compare(n1, n2) > 0)
{
return 1;
}
else if (String.Compare(n1, n2) <>
{
return -1;
}
else
{
return 0;
}
}
public override string ToString()
{
return FirstName + " " + LastName;
}
}
Events
A C# event is a class member that is activated whenever the event it was designed for occurs. I like to use the term "fires" when the event is activated. Anyone interested in the event can register and be notified as soon as the event fires. At the time an event fires, registered methods will be invoked.
Events and delegates work hand-in-hand to provide a program's functionality. It starts with a class that declares an event. Any class, including the same class that the event is declared in, may register one of its methods for the event. This occurs through a delegate, which specifies the signature of the method that is registered for the event. The delegate may be one of the pre-defined .NET delegates or one you declare yourself. Whichever is appropriate, you assign the delegate to the event, which effectively registers the method that will be called when the event fires.
using System;
using System.Drawing;
using System.Windows.Forms;
// an EventHandler delegate is assigned
// to the button's Click event
clickMe.Click += new EventHandler(OnClickMeClicked);
// our custom "Startdelegate" delegate is assigned
// to our custom "StartEvent" event.
StartEvent += new Startdelegate(OnStartEvent);
// fire our custom event
StartEvent();
}
// this method is called when the "clickMe" button is pressed
publicvoid OnClickMeClicked(object sender, EventArgs ea)
{
MessageBox.Show("You Clicked My Button!");
}
// this method is called when the "StartEvent" Event is fired
publicvoid OnStartEvent()
{
MessageBox.Show("I Just Started!");
}
staticvoid Main(string[] args)
{
Application.Run(new Eventdemo());
}
}
A string is generally understood as a data type storing a sequence of data values, usually bytes, in which elements usually stand for characters according to a character encoding, which differentiates it from the more general array data type. In this context, the terms binary string and byte string are used to suggest strings in which the stored data does not (necessarily) represent text.
Regular Expressions is a formatted string. Regular expressions (or REs) are essentially a tiny, highly specialized programming language. Regular expression patterns are compiled into a series of bytecodes which are then executed by a matching engine written in C. For advanced use, it may be necessary to pay careful attention to how the engine will execute a given RE, and write the RE in a certain way in order to produce bytecode that runs faster. Optimization isn't covered in this document, because it requires that you have a good understanding of the matching engine's internals.
Arrays are good for many tasks, but C# v2.0 introduced a new feature called generics. Among many benefits, one huge benefit is that generics allow us to create collections that allow us to do more than allow by an array.
In .NET v1.0 there were collections, such as the ArrayList for working with groups of objects. An ArrayList is much like an array, except it could automatically grow and offered many convenience methods that arrays don't have. The problem with ArrayList and all the other .NET v1.0 collections is that they operate on type object. Since all objects derive from the object type, you can assign anything to an ArrayList. The problem with this is that you incur performance overhead converting value type objects to and from the object type and a single ArrayList could accidentally hold different types, which would cause a hard to find errors at runtime because you wrote code to work with one type. Generic collections fix these problems.
A generic collection is strongly typed (type safe), meaning that you can only put one type of object into it. This eliminates type mismatches at runtime. Another benefit of type safety is that performance is better with value type objects because they don't incur overhead of being converted to and from type object. With generic collections, you have the best of all worlds because they are strongly typed, like arrays, and you have the additional functionality, like ArrayList and other non-generic collections, without the problems.
Version 2.0 of the .NET Framework class library provides a new namespace, System.Collections.Generic, which includes several ready-to-use generic collection classes and associated interfaces. Other namespaces such as System also provide new generic interfaces such as IComparable. These classes and interfaces are more efficient and type-safe than the non-generic collection classes provided in earlier releases of the .NET Framework. Before designing and implementing your own custom collection classes, consider whether you can use or derive a class from one of the classes provided in the base class library.
System.Collections.Generic namespace contains numerous class and interface types that allow you to contain subitems in a variety of containers.
The System.Collections.Generic namespace also defines a number of "helper" classes and structures that work in conjunction with a specific container. For example, the LinkedListNode type represents a node within a generic LinkedList, the KeyNotFoundException exception is raised when attempting to grab an item from a container using a nonexistent key, and so forth.
Use the generic LinkedList class. The following method creates a LinkedList class, adds nodes to this linked list object, and then uses several methods to obtain information from nodes within the linked list:
publicstaticvoid UseLinkedList()
{
// Create a new LinkedList object.
LinkedList todoList = new LinkedList();
// Create TodoItem objects to add to the linked list.
TodoItem i1 = new TodoItem("paint door", "Should be done third");
TodoItem i2 = new TodoItem("buy door", "Should be done first");
TodoItem i3 = new TodoItem("assemble door", "Should be done second");
TodoItem i4 = new TodoItem("hang door", "Should be done last");
In the LinkedList class, the previous node is always accessed through the Previous property and the next node is always accessed through the Next property. The first node’s Previous property in the linked list always returns a null value. Likewise, the last node’s Next property in the linked list always returns a null value.
Each node in the linked list is actually a generic LinkedListNode object. So a LinkedList object is actually a collection of LinkedListNode objects. Each of these LinkedListNode objects contains properties to access the next and previous LinkedListNode objects, as well as the object contained within it. The object contained in the LinkedListNode object is accessed through the Value property. In addition to these properties, a LinkedListNode object also contains a property called List, which allows access to the containing LinkedList object.
The KeyedCollection, ReadOnlyCollection, and Collection classes are not in the System.Collections.Generic namespace. These classes were moved to the System.Collections.ObjectModel namespace late in the development of version 2.0 of the .NET Framework. The rationale behind this move seemed to come about as a result of concern about creating some confusion for VB developers. The default Microsoft.VisualBasic namespace already included a Collection class, and thus making System.Generics.Collection a default namespace would cause IntelliSense to display two separate collection types for VB developers. To resolve this, the BCL team had the choice of renaming the Collection class or moving it to a new namespace. This is what gave rise to the new System.Collections.ObjectModel namespace.
·Threading
The threads of a computer program allow the program to execute sequential actions or many actions at once. Each thread in a program identifies a process that runs when the program asks it to.
Each process consist of one or more thread. These process can whole or part of the application/ program. A thread is a set of instruction or specific section of application that executes independently within the application or system. This can be also thought as the context in which code runs. So threads are basically light weight processes responsible for multitasking within a single application. Usually OS takes care of scheduling and execution of various threads.
When the system is build on various threads to perform multiple tasks to achieve parallelism and improve the efficiency of the system. This is the ability of any system to do multiple tasks simultaneously. Threads are implementing when there are situations in which more than one task at a time need to be completed.
Some of the benefits of threading are mentioned as follows:
* Using threads the long duration tasks in application can be processed at the background
* User interface can be made more appealing so that there is some task performed during various events like when the user clicks button for the processing some action a progress bar can be shown to show the progress of activity.
* Speed of the application can be increased.
* Threads can be useful in situations where there are gaps between tasks waiting for some event such as user input, file read, or receipt of data over the network. During the situation we can release various precious resources like memory usages etc
oThread Synchronization
As you write a threaded application, you may need to synchronize individual threads with other parts of your program. Synchronization provides a compromise between the unstructured nature of multithreaded programming and the structured order of synchronous processing.
Thread synchronization requires that a running thread gain a "lock" on an object before it can access it. The thread will wait in line for another thread that is using the method/data member to be done with it. This is very important to prevent the corruption of program data if multiple threads will be accessing the same data. If two threads try to change a variable or execute the same method at the same, this can cause serious and difficult to find problems. Thread synchronization helps prevent this.
oThread Safety in Windows Forms
Thread safety is a computer programming concept applicable in the context of multi-threaded programs. A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads. In particular, it must satisfy the need for multiple threads to access the same shared data, and the need for a shared piece of data to be accessed by only one thread at any given time.
·Files and Streams
A stream is an abstraction of a sequence of bytes. This sequence of bytes may come from a file, a TCP/IP socket, or memory. In .NET, a stream is represented, aptly, by the Stream class. The Stream class provides a generic view of a sequence of bytes. A Stream class forms the abstract class of all other streams. That is, you cannot directly create an instance of the Stream class. Instead, the Stream class is implemented by the following classes:
1. BufferedStream: provides a buffering layer on another stream to improve performance.
2. FileStream: provides a way to read and write files.
3. MemoryStream: provides a stream using memory as the backing store.
4. NetworkStream: provides a way to access data on the network.
5. CryptoStream: provides a way to supply data for cryptographic transformation.
Streams fundamentally involve the following operations:
1. Reading
2. Writing
3. Seeking
oWorking with Files and Directories
The .NET Framework comes fully equipped with a set of classes to carry out basic file system tasks—creating and reading directories, checking to see if files exist, retrieving file properties, and so on. Most of this magic takes place through two built-in objects, the FileInfo() object and the DirectoryInfo() object, both part of the System.IO namespace.
In this article, I will introduce you to these two objects. I'll show you how to read directories, retrieve file properties, and create a Windows Explorer clone that dynamically generates directory listings and file information.
All .NET stream classes are derived from the abstract class System.IO.Stream. Derived classes typically override the properties and methods to read from or write to a particular device. The .NET Framework implements the following stream classes:
* System.IO.FileStream reads and writes files.
* System.IO.MemoryStream can be used to read and write data in memory.
* System.Net.Sockets.NetworkStream is used to read data from and write data to the network, including across the Internet.
* System.Security.Cryptography.CryptoStream links streams to cryptographic transformations.
In addition, System.IO.BufferedStream allows you to compose a buffer around another stream to reduce the number of calls to the operating system and thus increase performance.
A stream is an abstraction of a sequence of bytes, such as you'd read from or write to a file, a network connection, or an I/O device. The Stream class and its derived classes provide a generic view of the data while insulating the programmer from the underlying operating system or particular I/O device.
As pointed out earlier, a stream is a sequence of bytes. All stream operations work in terms of bytes. Length returns the size of the stream in bytes. Read returns the data into an array of bytes, and Write writes data to the stream from an array of bytes. Once you've read data from the stream you can manipulate the array of bytes: converting it to a string or constructing data structures.
The example below reads data from a FileStream into an array of bytes and then converts the data to a String.
Cryptography is the art and science of keeping messages secure.
When a message is transferred from one place to another, it contents are readily available to an eavesdropper. A simple network-monitoring tool can expose the entire message sent from one computer
to another in a graphical way. For an N-Tier or distributed application to be secure, all messages sent on the network should be scrambled in a way that it is computationally impossible for any one to read it.
In cryptography world the message that needs to be secured is called plaintext or cleartext. The scrambled form of the message is called ciphertext. The process of converting a plaintext to ciphertext is called encryption. The process of reconverting the ciphertext into plaintext is called decryption. Cryptography algorithms (ciphers) are mathematical functions used for encryption and decryptions.
For cryptography to be used in practical solutions algorithms used for encryption and decryption should be made public. This is possible by using a byte stream called Key. For the algorithm to encipher a plaintext to ciphertext and to decipher it back to plaintext it needs Key.
Symmetric Key Encryption
Symmetric key encryption uses same key, called secret key, for both encryption and decryption. Users exchanging data keep this key to themselves. Message encrypted with a secret key can be decrypted only with the same secret key.
Asymmetric Key Encryption
Asymmetric key encryption uses different keys for encryption and decryption. These two keys are mathematically related and they form a key pair. One of these two keys should be kept private, called private-key, and the other can be made public (it can even be sent in mail), called public-key. Hence this is also called Public Key Encryption.
Cryptography in Microsoft .NET
Microsoft.NET has classes that extend the cryptographic services provided by Windows CryptoAPI.
System.Security.Cryptography namespace of Common Language runtime provides classes for
1. Symmetric Key Encryption
2. Asymmetric Key Encryption
3. Hashing
4. Digital Certificates
5. XML Signatures
Symmetric Key Encryption and Asymmetric Key Encryption are discussed in this article. Hashing, Digital Certificates and XML Signatures will be discussed is the subsequent articles.
oCompressions for Stream.Objects
Xceed Streaming Compression for .NET is an ASP component through which compression of data in .NET and ASP.net application can be done. This offers various features like compressing XML data, compressing data to store in the database, helps in continuous use of server, supporting Deflate64T, Deflate, Zlib, Glib format for compressing data and more.
Serialization is a process of converting an object into a stream of data so that it can be is easily transmittable over the network or can be continued in a persistent storage location. This storage location can be a physical file, database or ASP.NET Cache. Serialization is the technology that enables an object to be converted into a linear stream of data that can be easily passed across process boundaries and machines. This stream of data needs to be in a format that can be understood by both ends of a communication channel so that the object can be serialized and reconstructed easily. The advantage of serialization is the ability to transmit data across the network in a cross-platform-compatible format, as well as saving it in a persistent or non-persistent storage medium in a non-proprietary format. Serialization is used by Remoting, Web Services SOAP for transmitting data between a server and a client. De-serialization is the reverse; it is the process of reconstructing the same object later. The Remoting technology of .NET makes use of serialization to pass objects by value from one application domain to another. In this article I will discuss .NET's support for Serialization and how we can build a class that supports custom serialization.
Serialization in .NET is provided by the System.Runtime.Serialization namespace. This namespace contains an interface called IFormatter which in turn contains the methods Serialize and De-serialize that can be used to save and load data to and from a stream. In order to implement serialization in .NET, we basically require a stream and a formatter. While the stream acts as a container for the serialized object(s), the formatter is used to serialize these objects onto the stream.
The basic advantage of serialization is the ability of an object to be serialized into a persistent or a non-persistent storage media and then reconstructing the same object if required at a later point of time by de-serializing the object. Remoting and Web Services depend heavily on Serialization and De-serialization. Refer to the figure below.
Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. Exceptions are defined as anomalies that occur during the execution of a program. The .NET framework provides a rich set of standard exceptions that are used during exceptions handling. Exception handling is one of the major feature provide by .NET. There might be various reason to handle exception, this can be caused due to improper user inputs, improper design logic or system errors. In this scenario if application do not provide a mechanism to handle these anomalies then there might be cases the application may crash. .NET run time environment provide a default mechanism, which terminates the program execution.
This article provides insight about exception handling on the basis of ASP.NET and C# as code behind.
In ASP.NET exception handling is achieved using the Try ? Catch ? Finally block. All the three are ASP.NET keywords and are used do exception handling. The try block encloses the statements that might throw an exception whereas catch block handles any exception if one exists. The finally block can be used for doing any clean up process. Any general ASP.NET exception forces the application to terminate without allowing the code to continue executing, resulting in an error page.
Any custom exception you create needs to derive from the System.Exception class. You can either derive directly from it or use an intermediate exception like SystemException or ApplicationException as base class. According to the .NET framework documentation, SystemException is meant only for those exceptions defined by the common language runtime whereas ApplicationException is intended to be used by user code:
Arrays are very useful for holding lots of values under the same name. But there is also something called a Collection that does a similar job. In fact, there's an inbuilt group of Classes in C# specifically for Collections. They can be quite powerful.
With an array, you store data of the same type. So one array can only hold, say, numbers, but not letter. And an array set up as string can't hold numbers. So you can't do this, for example:
arrayPos[0] = 1;
arrayPos[1] = "two";
The first position holds a number and the second position holds text. C# won't let you do this in an array. But you can do it in a collection known as a Hashtable.
Collections can also make it easier to do things like sorting the data in your lists, deleting items, and adding more items. We'll start with the collection class called ArrayLists.
ArrayLists
You use an ArrayList when your collection may need items adding to it, deleting from it, or needs sorting. For example, suppose you are teacher with a class of ten children. You could keep a list of the children's names, add new students, delete ones who leave, and even sort them into brightest and dimmest! If you used a normal array, it would be difficult to do these things.
·Language Integrated Query (LINQ)
Commonly, data is stored in a database, but there are many other forms of accessing and manipulating data as well such as data files, event logs, the Registry, and so forth. Querying and manipulating data is a common part of many applications.
LINQ (often overheard pronounced as "link") is a step in the evolution of data access. It is a programming model that brings a much needed uniformity to accessing data from files, XML, database, registry, event log, and a whole host of other sources of data such as Active Directory and even services from 3rd parties such as Flickr. It is designed to work with all shapes and sizes of different data and allow you to perform Query, Set, and Transform operations on all of it. Pretty much anything that implements IEnumerable is a target for LINQ.
Language-Integrated Query (LINQ) is a new feature introduced in visual studio 2008 and .NET Framework 3.5. Developers can write the queries in the code to retrieve the data from various types of data sources like SQL,XML and XQuery.
Earlier developers has to learn the syntax for writing queries for each data source. LINQ simplifies by offering a model to work with the data across various kinds of data sources.
Important thing to notice is when write a query it do not retrieve any data. In order to get the data from data source you need to execute the query.
The data source in the above example is Array and implicitly supports IEnumerable interface. All types that support IEnumerable are called queryable types.
Query expression contains three clauses from, where and select.
The from clause specifies the data source, where clause applies the filter and select clause specifies the types of returned elements.
Query executes in foreach statement in the example. The actual execution of the query starts when iterate over the query variable in foreach statement.
oLINQ to Objects
LINQ to Objects allows .NET developers to write “queries” over collections of objects. Out of the box there is a large set of query operators that provide a similar depth of functionality to what we expect from any SQL language working with a relational database, and if what we need isn’t present out-of-the-box, we can add our own.
Traditionally, working with collections of objects meant writing a lot of looping code using for loops or foreach loops to iterate through a list carrying out filtering using if statements, and some action like keeping a running sum of a total property. LINQ frees you from having to write looping code; it allows you to write queries that filter a list or calculate aggregate functions on elements in a collection as a set.
We can write queries against any collection type that implements an interface called IEnumerable (and also a new interface called IQueryable, but more on that later). This is almost any collection type built into the .NET class libraries including simple arrays like string[], or int[], and any List collection we define. Let us look at a few of the simplest examples to understand the basic syntax.
With the introduction of LINQ to DataSet there finally exists a full featured query language for the DataSet. Now your ability to query your data is limited only by CLR, which is no small thing! For an introduction on LINQ to DataSet, please see this post.
This is great new functionality, but for most applications, query is only half of the story. Once you have sliced and diced your data into the form that you want, you need to do something with this data. This might be something as simple as spitting it out to the console, or as complex as binding it to a read/write hierarchical DataGrid. With this wide range of needs comes a wide range of capabilities.
This blog post will talk about how to do data binding with LINQ to DataSet from a high level perspective. Future posts will go into more details on each particular technology, and how to use it in a variety of situations.
If you simply bind the results of a LINQ to DataSet query to a grid (or some other control), you will see the values from your query results. However, the results will be simple values – you will not get the benefits of the DataSet, such as change tracking, transparent updating when the DataSet is updated, etc. Some features may work some of the time, but your experience will be less than stellar.
Why is this? When a LINQ to DataSet query is executed, the result is an IEnumerable. How data binding will work depends on the type of the enumeration (the T). There are a number of possibilities, each with its own problem. If the query is a projection of something, such as anonymous types, then the results are “torn off” from the source DataTable. This means that when you edit the values, then source never gets updated –in essence no data binding is occurring. If the projection is a DataRow, then you will get tracking for those DataRows, but because you are not bound to the DataTable, you end up not being able to add/delete DataRows!
var query = from order in adventureWorksDS1.SalesOrderHeader
where order.IsCreditCardIDNull() == false
orderby order.OrderDate descending
select order;
dataGridView1.DataSource = query.AsDataView();
oLINQ to XML
LINQ to XML is a new way to construct, write and read XML data in the .NET language of the developers’ choice. This new API simplifies working with XML data without having to resort to using additional language syntax like XPath or XSLT. LINQ to XML is not a replacement for any of the current DOM’s or XML class libraries; LINQ to XML in many cases overlaps their functionality and aims to provide a superior developer experience, but existing code will continue to work. One aspect of LINQ to XML is that it supports writing Query Expressions and can be combined with any of the other LINQ technologies to create or use XML data as a source or destination format.
LINQ to SQL allows .NET developers to write “queries” in their .NET language of choice to retrieve and manipulate data from a SQL Server database. In a general sense, LINQ to SQL allows us to create SQL queries in our preferred .NET language syntax and work with a strongly types collection of objects as a return result. We can make changes to these objects then save changes back to the database.
To get an idea of the syntax for LINQ to SQL, we will be using the following SQL database schema. It is a simple software registration and helpdesk. It is populated with sample data and has foreign-key relationships defined where appropriate.
HookedOnLINQ db =
new HookedOnLINQ("Data Source=(local);Initial Catalog=HookedOnLINQ");