Docstoc

c sharp

Document Sample
c sharp Powered By Docstoc
					How we can perform cross language inheritance in .Net? Give Proper Reason also.
.NET provides us with a concept of Assembly manifest and meta-data that could provide enough information to
inherit a class in another language.

The main advantages of doing cross-language inheritance is that it facilitates debugging. You can simply run the
debugger and CLR will allow you to trace from one language to the next automatically. Needless to say, we can
create a rich set of class libraries.

Here is a program with a C# Class:

using System
using System.Data;
using System.Data.SQL;
using System.Collections;

namespace LibraryCS
{

private int AuId;
public class Author
{
public Author(int myId)
{
AuId = myId;
}
public int TotalSalesForAuthor(int myId)
{
SqlConnection conn = new SqlConnection(connstr);
conn.ConnectionString = "database=northwind;server=mySQLServer” conn.Open();

string str = “select sum(ytd_sales) as TotalSales from titles inner join titleauthor on titles.title_id = titleauthor.title_id
where au_id = “ + myid;
SqlCommand comm. = new SqlCommand( sqlstr, conn);
SqlDataReader myReader = myCommand.ExecuteReader();
myReader.Read();
return myReader.GetInt32(0);
myReader.Close();
conn.Close();
}
}
}

Let us derive another class from the above class. This will be in VB.NET.

Option Explicit
Option Strict

Imports LibraryCS
Namespace subLibClass

Public class PubAuthor inherits Author

Public overrides function TotalSalesForAuthor (auid as string) as integer
Dim iSalesTotal as integer
ISalesTotal = MyBase.TotalSalesForAuthor(auid);
Return Cint(iSalesTotal * 0.65)
End Function

End Class

End Namespace

Some of the key points we need to keep in mind doing this cross-language inheritance.

1)We must add the virtual modifier to the function declaration in the parent C# class.
public virtual int TotalSalesForAuthor(int myId)
{
SqlConnection conn = new SqlConnection(connstr);
-------------
-------------
-------------
}

2)We need to import the namespace since the references to that class are made in the new component.
3)The class names need to unique only within the same namespace. But In this example, we have used different
namespaces altogether.
4)The only method in the derived class is the one we need to override. All other properties and methods from the
parent class automatically become public members of the derived class.
5)The overrides keyword in the function of the derived class indicates that this will replace the base class version of
this function.

Conclusion

There are so many wonderful applications lying unused in computer departments as they failed to serve their
masters’ current day’s needs. Technologically, they are labeled as “outdated.” But, from our part, we are committing
a mistake of not giving enough refreshing to them. In the recent days, developers are urged to migrate the existing
applications to the latest technology and the cross-language inheritance facility in .NET, to me, is the right babe for
doing so.



What is ILasm exe used for?

The MSIL Assembler generates a portable executable (PE) file from Microsoft intermediate language (MSIL). (For
more information on MSIL, see Managed Execution Process.) You can run the resulting executable, which contains
MSIL and the required metadata, to determine whether the MSIL performs as expected.
This tool is automatically installed with Visual Studio and with the Windows SDK. To run the tool, we recommend
that you use the Visual Studio Command Prompt or the Windows SDK Command Prompt (CMD Shell). These utilities
enable you to run the tool easily, without navigating to the installation folder. For more information, see Visual
Studio and Windows SDK Command Prompts.

       If you have Visual Studio installed on your computer: On the taskbar, click Start, click All Programs, click
        Visual Studio, click Visual Studio Tools, and then click Visual Studio Command Prompt.

        -or-

        If you have the Windows SDK installed on your computer: On the taskbar, click Start, click All Programs, click
        the folder for the Windows SDK, and then click Command Prompt (or CMD Shell).

       At the command prompt, type the following:

ilasm [options] filename [[options]filename...]



What is MSIL?
MSIL stands for Microsoft Intermediate Language.

When compiling the source code to managed code in dotnet environment, the compiler translates the source into
Microsoft intermediate language (MSIL). This is a CPU- independent set of instructions that can efficiently be
converted to native code. Microsoft intermediate language (MSIL) is a translation used as the output of a number of
compilers. It is the input to a just-in-time (JIT) compiler. The Common Language Runtime includes a JIT compiler for
the conversion of MSIL to native code.



How to: View Assembly Contents
You can use the Ildasm.exe (MSIL Disassembler) to view Microsoft intermediate language (MSIL) information in a file.
If the file being examined is an assembly, this information can include the assembly's attributes, as well as references
to other modules and assemblies. This information can be helpful in determining whether a file is an assembly or
part of an assembly, and whether the file has references to other modules or assemblies.

To display the contents of an assembly using Ildasm.exe

       Type ildasm <assembly name> at the command prompt. For example, the following command disassembles
        the Hello.exe assembly.
       ildasm Hello.exe

To view assembly manifest information

       Double-click the MANIFEST icon in the MSIL Disassembler window.




Dictionary
using   System;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;
using   System.Collections;
namespace UsingDictionary
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList books = new ArrayList();
            books.Add(new Book { Title = "C Programming", Author = "Yashwant", Price = 500,
Publisher = "TMG" });
            books.Add(new Book { Title = "J2ME", Author = "Bryan", Price = 700, Publisher = "PHI"
});
            books.Add(new Book { Title = "Advanced .NET", Author = "Rajaraman", Price = 880,
Publisher = "TMG" });
            books.Add(new Book { Title = "PHP", Author = "John", Price = 560, Publisher = "Apress"
});

              //Book[] bookArray = (Book[])books.ToArray(typeof(Book));

              //Book[] bookAray = new Book[100];

              Dictionary<string, float> bookDictionary =
                          ((Book[])books.ToArray(typeof(Book)))
                          .ToDictionary(b => b.Title,
                              p => p.Price);

              Console.WriteLine(bookDictionary["PHP"]);
              Console.WriteLine(bookDictionary["Advanced .NET"]);
              Console.WriteLine("______________");
              Dictionary<string, string> bookDictionary1 =
                          ((Book[])books.ToArray(typeof(Book)))
                          .ToDictionary(b => b.Title,
                              p => p.Title);
              Console.WriteLine(bookDictionary1["PHP"]);
              Console.WriteLine(bookDictionary1["Advanced .NET"]);

              Console.ReadKey();
          }
    }
    public class Book
    {
        public string Title { get; set; }
        public string Author { get; set; }
        public float Price { get; set; }
        public string Publisher { get; set; }
    }
}

Operator Overloading
using   System;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;

namespace OperatorOverloading
{
    class test
    {
        public int n1,n2;
        public test(){}
        public test(int no1, int no2)
        {
            this.n1 = no1;
            this.n2 = no2;
        }
        public static test operator +(test t1, test t2)
        {
            test temp=new test();
              temp.n1 = t1.n1 + t2.n1;
              temp.n2 = t1.n2 + t2.n2;
              return temp;
         }
         public static test operator -(test t)
         {
             test temp = new test();
             temp.n1 = -t.n1;
             temp.n2 = -t.n2;
             return temp;
         }
    }
    class Program
    {
        static void Main(string[] args)
        {
            test t1 = new test(10, 30);
            test t2 = new test(20, 25);
            test t3=t1+t2;
            t3=-t3;
            Console.WriteLine("t1 has : {0} {1}", t1.n1, t1.n2);
            Console.WriteLine("t2 has : {0} {1}", t2.n1, t2.n2);
            Console.WriteLine("t3 has : {0} {1}", t3.n1, t3.n2);
            Console.ReadKey();
        }
    }
}



GUID

GUID stands for Global Unique Identifier.

A GUID is a 128-bit integer (16 bytes) that you can use across all computers and networks wherever a unique
identifier is required.

Here are some frequently asked questions about GUIDs.

A. How many GUIDs in Microsoft Windows can one computer generate without rolling over or running out?

Answer: Without getting into detail, let me tell you there are 2^122 or
5,316,911,983,139,663,491,615,228,241,121,400,000 possible combination.

Reason is beyond the scope of this article.



B. Which class in .NET Framework is used to generate Guid?

Answer: System.GUID class represents a GUID in .NET Framework.



C. How can we generate GUID with SQL Server?

Answer: We can generate GUID in Sql Server with the help of NEWID() function

D. Which namespace must be referenced to utilize the GUID attribute. ?

Answer: System.Runtime.InteropServices namespace must be referenced to utilize the GUID attribute.
Generating GUID in .NET Framework using C#

We can generate GUID by calling following code snippet. As you can see from this code, we use Guid.NewGuid()
method to generate a new GUID in C#.

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

namespace ConsoleApplication5
{

    class Program
    {
       static int Main(string[] args)
       {
            Guid obj = Guid.NewGuid();

            Console.WriteLine("New Guid is " + obj.ToString());
            Console.ReadLine();
            return -1;
        }
    }
}


Note that above in above code we have used the NewGuid Method which will create new GUID .

A common mistake done by C# developers is to create an object of GUID and trying to print that.



Inheritance

One of the absolute key aspects of Object Oriented Programming (OOP), which is the concept that C# is built upon, is
inheritance, the ability to create classes which inherits certain aspects from parent classes. The entire .NET
framework is built on this concept, with the "everything is an object" as a result of it. Even a simple number is an
instance of a class, which inherits from the System.Object class, although .NET helps you out a bit, so you can assign
a number directly, instead of having to create a new instance of e.g. the integer class.

This subject can be a bit difficult to comprehend, but sometimes it help with some examples, so let's start with a
simple one of those:
public class Animal
{
  public void Greet()
  {
     Console.WriteLine("Hello, I'm some sort of animal!");
  }
}

public class Dog : Animal
{

}
First, we define an Animal class, with a simple method to output a greeting. Then we define a Dog class, and with a
colon, we tell C# that the Dog class should inherit from the Animal class. The beautiful thing about this is that it
makes sense in the real world as well - a Dog is, obviously, an Animal. Let's try using the classes:
Animal animal = new Animal();
animal.Greet();
Dog dog = new Dog();
dog.Greet();
If you run this example, you will notice that even though we have not defined a Greet() method for the Dog class, it
still knows how to greet us, because it inherits this method from the Animal class. However, this greeting is a bit
anonymous, so let's customize it when we know which animal it is:
public class Animal
{
   public virtual void Greet()
   {
      Console.WriteLine("Hello, I'm some sort of animal!");
   }
}

public class Dog : Animal
{
  public override void Greet()
  {
    Console.WriteLine("Hello, I'm a dog!");
  }
}
Besides the added method on the Dog class, you should notice two things: I have added the virtual keyword to the
method on the Animal class, and on the Dog class, I use the override keyword.

In C#, you are not allowed to override a member of a class unless it's marked as virtual. If you want to, you can still
access the inherited method, even when you override it, using the base keyword.

public override void Greet()
{
  base.Greet();
  Console.WriteLine("Yes I am - a dog!");
}

Methods is not the only thing to get inherited, though. In fact, pretty much all class members will be inherited,
including fields and properties. Just remember the rules of visibilty, as discussed in a previous chapter.

Inheritance is not only from one class to another - you can have a whole hierarchy of classes, which inherits from
eachother. For instance, we could create a Puppy class, which inherits from our Dog class, which in turn inherits from
the Animal class. What you can't do in C#, is to let one class inherit from several other classes at the same time.
Multiple inheritance, as it's called, is not supported by C#.



Abstraction

The word abstract means a concept or an idea not associated with any specific instance.

In programming we apply the same meaning of abstraction by making classes not associated with any specific
instance.

The abstraction is done when we need to only inherit from a certain class, but not need to instantiate objects of that
class. In such case the base
class can be regarded as "Incomplete". Such classes are known as an "Abstract Base Class".

Abstract Base Class

There are some important points about Abstract Base Class :

    1. An Abstract Base class can not be instantiated; it means the object of that class can not be created.

    2. Class having abstract keyword and having, abstract keyword with some of its methods (not all) is known as
       an Abstract Base Class.

    3. Class having Abstract keyword and having abstract keyword with all of its methods is known as pure Abstract
       Base Class.

    4. The method of abstract class that has no implementation is known as "operation". It can be defined as
       abstract void method ();

    5. An abstract class holds the methods but the actual implementation of those methods is made in derived
       class.


Lets have a look of this code!

  abstract class animal
  {
     public abstract void eat();
     public void sound()
     {
        Console.WriteLine("dog can sound");
     }
  }
This is the Abstract Base Class, if I make both of its methods abstract then this class would become a pure Abstract
Base Class.

Now we derive a class of 'dog' from the class animal.

  abstract class animal
  {
     public abstract void eat();
     public void sound()
     {
       Console.WriteLine("dog can sound");
     }
  }
  class dog : animal
  {
     public override void eat() { Console.WriteLine("dog can eat"); }
  }

Here you can see we have 2 methods in the Abstract Base Class, the method eat() has no implementation; that is
why it is being declared as 'abstract' while the method sound() has its own body so it is not declared as 'abstract'.

In the derived class we have the same name method but this method has it's body.

We are doing abstraction here so that we can access the method of derived class without any trouble.

Let's have a look!
  class program
  {
     abstract class animal
     {
        public abstract void eat();
        public void sound()
        {
          Console.WriteLine("dog can sound");
        }
     }
     class dog : animal
     {
        public override void eat() { Console.WriteLine("dog can eat"); }
     }
     static void Main(string[] args)
     {
        dog mydog = new dog();
        animal thePet = mydog;
        thePet.eat();
        mydog.sound();
     }
  }

Finally we created an Object 'mydog' of class dog, but we didn't instantiate any object of Abstract Base Class
'animal'.

According to "Ivor Horton" (a programmer of Java) an object can not be instantiated, but we can declare a variable
of the Abstract Class type. If this statement is true then it could be possible:

animal thePet;

This is an object which is declared as thePet and its data type is the abstract base class 'animal'.

We can use this Object to store Objects of the subclass.

In the above code we declare an Object 'thePet', of the type animal (the Abstract Base Class) and simply copied the
object of another object (only the reference is copied as they belong to reference type). Now we can use object
'thePet' just as object 'mydog'.

The output of this code would be as

dog can eat
dog can sound

Conclusion:

l conclude here by saying that Abstraction is not a difficult job to do, but you need to be confident while performing
abstraction. Our every new topic covers the all previous topics. In the abstraction the polymorphism is being covered
and performed. The method overriding could be done by putting the keyword 'new' before that overridden method.
Everything is possible in Programming and there are multiple ways to do a single job. Abstraction is one of the smart
ways to do these kind of tasks.
What is the .NET Framework?

The .NET Framework is a new and revolutionary platform created by Microsoft for developing applications.

           It is a platform for application developers.
           It is a Framework that supports Multiple Language and Cross language integration.
           IT has IDE (Integrated Development Environment).
           Framework is a set of utilities or can say building blocks of your application system.
           .NET Framework provides GUI in a GUI manner.
           .NET is a platform independent but with help of Mono Compilation System (MCS). MCS is a middle level
            interface.
           .NET Framework provides interoperability between languages i.e. Common Type System (CTS) .
           .NET Framework also includes the .NET Common Language Runtime (CLR), which is responsible for
            maintaining the execution of all applications developed using the .NET library.
           The .NET Framework consists primarily of a gigantic library of code.

Definition: A programming infrastructure created by Microsoft for building, deploying, and running applications and
services that use .NET technologies, such as desktop applications and Web services.

Cross Language integration

You can use a utility of a language in another language (It uses Class Language Integration).

.NET Framework includes no restriction on the type of applications that are possible. The .NET Framework allows the
creation of Windows applications, Web applications, Web services, and lot more.

The .NET Framework has been designed so that it can be used from any language, including C#, C++, Visual Basic,
JScript, and even older languages such as COBOL.

Difference between Visual Studio and Visual Studio .NET

Visual Studio                                                Visual Studio
It is object based                                           It is object oriented
Internet based application                                   All developing facilities in internet based application
- Web Application
- Web services
- Internet enable application
- Third party API
- Peer to peer Application
Poor error handling Exception/Error                          Advance error handler and debugger
Memory Management System Level Task                          Memory Management Application Domain with help of
                                                             GC (Garbage Collector)
DLL HELL                                                     VS .NET has solved DLL HELL Problem

Simple explanation of definition used in the above comparision:

Web Application

All websites are example of web application. They use a web server.

Internet Enabled Application

They are desktop application. Yahoo messenger is an example of desktop application.

Peer to Peer
Communication through computers through some system.

Web Services

It doesn't use web-based server. Internet payment systems are example of web services.

DLL Hell

"DLL Hell" refers to the set of problems caused when multiple applications attempt to share a common component
like a dynamic link library (DLL) or a Component Object Model (COM) class.

The reason for this issue was that the version information about the different components of an application was not
recorded by the system. (Windows Registry cannot support the multiple versions of same COM component this is
called the dll hell problem.)

.Net Framework provides operating systems with a Global Assembly Cache (GAC). This Cache is a repository for all
the .Net components that are shared globally on a particular machine. When a .Net component is installed onto the
machine, the Global Assembly Cache looks at its version, its public key, and its language information and creates a
strong name for the component. The component is then registered in the repository and indexed by its strong name,
so there is no confusion between different versions of the same component, or DLL.

Architecture of .NET Framework




Architecture of CLR
CLS (Common Language Specification)

It is a subset of CTS. All instruction is in CLS i.e. instruction of CTS is written in CLS.

Code Manager

Code manager invokes class loader for execution.

.NET supports two kind of coding

1) Managed Code
2) Unmanaged Code

Managed Code

The resource, which is with in your application domain is, managed code. The resources that are within domain are
faster.

The code, which is developed in .NET framework, is known as managed code. This code is directly executed by CLR
with help of managed code execution. Any language that is written in .NET Framework is managed code.

Managed code uses CLR which in turns looks after your applications by managing memory, handling security,
allowing cross - language debugging, and so on.




Unmanaged Code

The code, which is developed outside .NET, Framework is known as unmanaged code.

Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as
C++ can be used to write such applications, which, for example, access low - level functions of the operating system.
Background compatibility with code of VB, ASP and COM are examples of unmanaged code.
Unmanaged code can be unmanaged source code and unmanaged compile code.

Unmanaged code is executed with help of wrapper classes.

Wrapper classes are of two types: CCW (COM callable wrapper) and RCW (Runtime Callable Wrapper).

Wrapper is used to cover difference with the help of CCW and RCW.
COM callable wrapper unmanaged code




Runtime Callable Wrapper unmanaged code




Native Code

The code to be executed must be converted into a language that the target operating system understands, known as
native code. This conversion is called compiling code, an act that is performed by a compiler.

Under the .NET Framework, however, this is a two - stage process. With help of MSIL and JIT.

MSIL (Microsoft Intermediate Language)
It is language independent code. When you compile code that uses the .NET Framework library, you don't
immediately create operating system - specific native code.

Instead, you compile your code into Microsoft Intermediate Language (MSIL) code. The MSIL code is not specific to
any operating system or to any language.

JIT (Just-in-Time)

Just - in - Time (JIT) compiler, which compiles MSIL into native code that is specific to the OS and machine
architecture being targeted. Only at this point can the OS execute the application. The just - in - time part of the
name reflects the fact that MSIL code is only compiled as, and when, it is needed.

In the past, it was often necessary to compile your code into several applications, each of which targeted a specific
operating system and CPU architecture. Often, this was a form of optimization.

This is now unnecessary, because JIT compilers (as their name suggests) use MSIL code, which is independent of the
machine, operating system, and CPU. Several JIT compilers exist, each targeting a different architecture, and the
appropriate one will be used to create the native code required.

The beauty of all this is that it requires a lot less work on your part - in fact, you can forget about system - dependent
details and concentrate on the more interesting functionality of your code.

JIT are of three types:

    1. Pre JIT
    2. Econo JIT
    3. Normal JIT

Pre JIT

It converts all the code in executable code and it is slow

Econo JIT

It will convert the called executable code only. But it will convert code every time when a code is called again.

Normal JIT

It will only convert the called code and will store in cache so that it will not require converting code again. Normal JIT
is fast.

Assemblies

When you compile an application, the MSIL code created is stored in an assembly. Assemblies include both
executable application files that you can run directly from Windows without the need for any other programs (these
have a .exe file extension), and libraries (which have a .dll extension) for use by other applications.

In addition to containing MSIL, assemblies also include meta information (that is, information about the information
contained in the assembly, also known as metadata) and optional resources (additional data used by the MSIL, such
as sound files and pictures).

The meta information enables assemblies to be fully self - descriptive. You need no other information to use an
assembly, meaning you avoid situations such as failing to add required data to the system registry and so on, which
was often a problem when developing with other platforms.
This means that deploying applications is often as simple as copying the files into a directory on a remote computer.
Because no additional information is required on the target systems, you can just run an executable file from this
directory and (assuming the .NET CLR is installed) you're good to go.

Of course, you won't necessarily want to include everything required to run an application in one place. You might
write some code that performs tasks required by multiple applications. In situations like that, it is often useful to
place the reusable code in a place accessible to all applications. In the .NET Framework, this is the Global Assembly
Cache (GAC). Placing code in the GAC is simple - you just place the assembly containing the code in the directory
containing this cache.

Garbage Collection (GC)

One of the most important features of managed code is the concept of garbage collection. This is the .NET method
of making sure that the memory used by an application is freed up completely when the application is no longer in
use.

Prior to .NET this was mostly the responsibility of programmers, and a few simple errors in code could result in large
blocks of memory mysteriously disappearing as a result of being allocated to the wrong place in memory. That
usually meant a progressive slowdown of your computer followed by a system crash.

.NET garbage collection works by inspecting the memory of your computer every so often and removing anything
from it that is no longer needed. There is no set time frame for this; it might happen thousands of times a second,
once every few seconds, or whenever, but you can rest assured that it will happen.

Will try to explain the processing in terms of C# code which is written using .NET Framework.

Step 1- Application code is written using a .NET - compatible language C#.




Step 2 - Code is compiled into MSIL, which is stored in an assembly (see Figure 1 - 2).




Step 3 - When this code is executed (either in its own right if it is an executable or when it is used from other code),
it must first be compiled into native code using a JIT compiler.




Step 4 - The native code is executed in the context of the managed CLR, along with any other running applications or
processes.




Note: One additional point concerning this process. The C# code that compiles into MSIL in step 2 needn't be
contained in a single file. It's possible to split application code across multiple source code files, which are then
compiled together into a single assembly. This extremely useful process is known as linking.
This is because it is far easier to work with several smaller files than one enormous one. You can separate out
logically related code into an individual file so that it can be worked on independently and then practically forgotten
about when completed.

This also makes it easy to locate specific pieces of code when you need them and enables teams of developers to
divide up the programming burden into manageable chunks, whereby individuals can check out pieces of code to
work on without risking damage to otherwise satisfactory sections or sections other people are working on.

Conclusion

I hope that this article would have helped you in understanding .NET Framework and have built a simple and clear
understanding of .NET.

Have taken some definition and lines from some references for technically explanation and understanding. Your
feedback and constructive contributions are welcome. Please feel free to contact me for feedback or comments you
may have about this article.


Interface
In previous chapters, we had a look at abstract classes. Interfaces are much like abstract classes and they share the
fact that no instances of them can be created. However, interfaces are even more conceptual than abstract classes,
since no method bodies are allowed at all. So an interface is kind of like an abstract class with nothing but abstract
methods, and since there are no methods with actual code, there is no need for any fields. Properties are allowed
though, as well as indexers and events. You can consider an interface as a contract - a class that implements it is
required to implement all of the methods and properties. However, the most important difference is that while C#
doesn't allow multiple inheritance, where classes inherit more than a single base class, it does in fact allow for
implementation of multiple interfaces!

So, how does all of this look in code? Here's a pretty complete example. Have a look, perhaps try it out on your own,
and then read on for the full explanation:

using System;
using System.Collections.Generic;

namespace Interfaces
{
  class Program
  {
     static void Main(string[] args)
     {
       List<Dog> dogs = new List<Dog>();
       dogs.Add(new Dog("Fido"));
       dogs.Add(new Dog("Bob"));
       dogs.Add(new Dog("Adam"));
       dogs.Sort();
       foreach(Dog dog in dogs)
          Console.WriteLine(dog.Describe());
       Console.ReadKey();
     }
  }

  interface IAnimal
  {
    string Describe();
        string Name
        {
           get;
           set;
        }
    }

    class Dog : IAnimal, IComparable
    {
       private string name;

        public Dog(string name)
        {
          this.Name = name;
        }

        public string Describe()
        {
          return "Hello, I'm a dog and my name is " + this.Name;
        }

        public int CompareTo(object obj)
        {
          if(obj is IAnimal)
             return this.Name.CompareTo((obj as IAnimal).Name);
          return 0;
        }

        public string Name
        {
          get { return name; }
          set { name = value; }
        }
    }
}

Let's start in the middle, where we declare the interface. As you can see, the only difference from a class declaration,
is the keyword used - interface instead of class. Also, the name of the interface is prefixed with an I for Interface -
this is simply a coding standard, and not a requirement. You can call your interfaces whatever you want, but since
they are used like classes so much that you might have a hard time telling the difference in some parts of your code,
the I prefix makes pretty good sense.

Then we declare the Describe method, and afterwards, the Name property, which has both a get and a set keyword,
making this a read and writeable property. You will also notice the lack of access modifiers (public, private, protected
etc.), and that's because they are not allowed in an interface - they are all public by default.

Next up is our Dog class. Notice how it looks just like inheriting from another class, with the colon between the class
name and the class/interface being subclassed/implemented. However, in this case, two interfaces are implemented
for the same class, simply separated by a comma. You can implement as many interfaces as you want to, but in this
case we only implement two - our own IAnimal interface, and the .NET IComparable interface, which is a shared
interface for classes that can be sorted. Now as you can see, we have implemented both the method and the
property from the IAnimal interface, as well as a CompareTo method from the IComparable interface.

Now you might be thinking: If we have to do all the work our self, by implementing the entire methods and
properties, why even bother? And a very good example of why it's worth your time, is given in the top of our
example. Here, we add a bunch of Dog objects to a list, and then we sort the list. And how does the list know how to
sort dogs? Because our Dog class has a CompareTo method that can tell how to compare two dogs. And how does
the list know that our Dog object can do just that, and which method to call to get the dogs compared? Because we
told it so, by implementing an interface that promises a CompareTo method! This is the real beauty of interfaces.


ADO .NET
Most applications need data access at one point of time making it a crucial component when working with
applications. Data access is making the application interact with a database, where all the data is stored. Different
applications have different requirements for database access. VB .NET uses ADO .NET (Active X Data Object) as it's
data access and manipulation protocol which also enables us to work with data on the Internet. Let's take a look why
ADO .NET came into picture replacing ADO.

Evolution of ADO.NET

The first data access model, DAO (data access model) was created for local databases with the built-in Jet engine
which had performance and functionality issues. Next came RDO (Remote Data Object) and ADO (Active Data
Object) which were designed for Client Server architectures but, soon ADO took over RDO. ADO was a good
architecture but as the language changes so is the technology. With ADO, all the data is contained in a recordset
object which had problems when implemented on the network and penetrating firewalls. ADO was a connected data
access, which means that when a connection to the database is established the connection remains open until the
application is closed. Leaving the connection open for the lifetime of the application raises concerns about database
security and network traffic. Also, as databases are becoming increasingly important and as they are serving more
people, a connected data access model makes us think about its productivity. For example, an application with
connected data access may do well when connected to two clients, the same may do poorly when connected to 10
and might be unusable when connected to 100 or more. Also, open database connections use system resources to a
maximum extent making the system performance less effective.

Why ADO.NET?

To cope up with some of the problems mentioned above, ADO .NET came into existence. ADO .NET addresses the
above mentioned problems by maintaining a disconnected database access model which means, when an
application interacts with the database, the connection is opened to serve the request of the application and is
closed as soon as the request is completed. Likewise, if a database is Updated, the connection is opened long enough
to complete the Update operation and is closed. By keeping connections open for only a minimum period of time,
ADO .NET conserves system resources and provides maximum security for databases and also has less impact on
system performance. Also, ADO .NET when interacting with the database uses XML and converts all the data into
XML format for database related operations making them more efficient.


The ADO.NET Data Architecture

Data Access in ADO.NET relies on two components: DataSet and Data Provider.

DataSet

The dataset is a disconnected, in-memory representation of data. It can be considered as a local copy of the relevant
portions of the database. The DataSet is persisted in memory and the data in it can be manipulated and updated
independent of the database. When the use of this DataSet is finished, changes can be made back to the central
database for updating. The data in DataSet can be loaded from any valid data source like Microsoft SQL server
database, an Oracle database or from a Microsoft Access database.

Data Provider
The Data Provider is responsible for providing and maintaining the connection to the database. A DataProvider is a
set of related components that work together to provide data in an efficient and performance driven manner. The
.NET Framework currently comes with two DataProviders: the SQL Data Provider which is designed only to work with
Microsoft's SQL Server 7.0 or later and the OleDb DataProvider which allows us to connect to other types of
databases like Access and Oracle. Each DataProvider consists of the following component classes:

The Connection object which provides a connection to the database
The Command object which is used to execute a command
The DataReader object which provides a forward-only, read only, connected recordset
The DataAdapter object which populates a disconnected DataSet with data and performs update


Data access with ADO.NET can be summarized as follows:

A connection object establishes the connection for the application with the database. The command object provides
direct execution of the command to the database. If the command returns more than a single value, the command
object returns a DataReader to provide the data. Alternatively, the DataAdapter can be used to fill the Dataset
object. The database can be updated using the command object or the DataAdapter.




Component classes that make up the Data Providers

The Connection Object

The Connection object creates the connection to the database. Microsoft Visual Studio .NET provides two types of
Connection classes: the SqlConnection object, which is designed specifically to connect to Microsoft SQL Server 7.0
or later, and the OleDbConnection object, which can provide connections to a wide range of database types like
Microsoft Access and Oracle. The Connection object contains all of the information required to open a connection to
the database.

The Command Object

The Command object is represented by two corresponding classes: SqlCommand and OleDbCommand. Command
objects are used to execute commands to a database across a data connection. The Command objects can be used
to execute stored procedures on the database, SQL commands, or return complete tables directly. Command objects
provide three methods that are used to execute commands on the database:

ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE or DELETE
ExecuteScalar: Returns a single value from a database query
ExecuteReader: Returns a result set by way of a DataReader object


The DataReader Object

The DataReader object provides a forward-only, read-only, connected stream recordset from a database. Unlike
other components of the Data Provider, DataReader objects cannot be directly instantiated. Rather, the DataReader
is returned as the result of the Command object's ExecuteReader method. The SqlCommand.ExecuteReader method
returns a SqlDataReader object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader
object. The DataReader can provide rows of data directly to application logic when you do not need to keep the data
cached in memory. Because only one row is in memory at a time, the DataReader provides the lowest overhead in
terms of system performance but requires the exclusive use of an open Connection object for the lifetime of the
DataReader.

The DataAdapter Object

The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is essentially the middleman
facilitating all communication between the database and a DataSet. The DataAdapter is used either to fill a
DataTable or DataSet with data from the database with it's Fill method. After the memory-resident data has been
manipulated, the DataAdapter can commit the changes to the database by calling the Update method. The
DataAdapter provides four properties that represent database commands:

SelectCommand
InsertCommand
DeleteCommand
UpdateCommand

When the Update method is called, changes in the DataSet are copied back to the database and the appropriate
InsertCommand, DeleteCommand, or UpdateCommand is executed.




XML Parsing

The application reads the XML file and then associates the xml tags to variables which are then displayed in a
message box.

The namespace System.Xml would be the only additional namespace that we would be using.

Start of by initializing a new instance of the XmlDocument class.

XmlDocument xDoc = new XmlDocument();

Next use the load method to load the XML document from the specified stream.

xDoc.Load("sampleXML.xml");

Use the method GetElementsByTagName() to obtain the addresses of a collection of elements that match the
specified name.
XmlNodeList name = xDoc.GetElementsByTagName("myName");
XmlNodeList age = xDoc.GetElementsByTagName("myAge");

XmlNodeList represents an ordered collection of nodes.

Display the results in a message box.

MessageBox.Show("Name: " + name[0].InnerText)

InnerText will return the concatenated values of the node and all its children.

Another Way Xml Parser with xmlreader

This project gives you a head start to write an XML parser in C#. The important namespace to achieve our goal is
System.Xml. Though you might find it strange, unlike other languages/class libraries their are no direct functions like
startElement and endElement to your rescue. You will have to manage all this on your own. So let's start looking at
this important block of the code

void ParseURL(string strUrl)
{
  try
  {
    XmlTextReader reader = new XmlTextReader(strUrl);
    while (reader.Read())
     {
       switch (reader.NodeType)
       {
       case XmlNodeType.Element:
          Hashtable attributes = new Hashtable();
          string strURI= reader.NamespaceURI;
          string strName= reader.Name;
          if (reader.HasAttributes)
          {
             for (int i = 0; i < reader.AttributeCount; i++)
             {
                reader.MoveToAttribute(i);
                attributes.Add(reader.Name,reader.Value);
             }
          }
          StartElement(strURI,strName,strName,attributes);
       break;
        //
        //you can handle other cases here
        //

        //case XmlNodeType.EndElement:
        // Todo
        //case XmlNodeType.Text:
        // Todo
        default:
        break;
    }
  }
  catch (XmlException e)
  {
    Console.WriteLine("error occured: " + e.Message);
    }
}

As we see the main class here is XmlTextReader. XmlTextReader provides forward-only, read-only access to a stream
of XML data. The current node refers to the node on which the reader is positioned. The reader is advanced using
any of the read methods and properties reflect the value of the current node. Note that we cache the element name
before we move to the attributes.

The NodeType property of XmlTextReader gets the type of the current node. Accordingly we process the node and
call necessary functions on it.




Another way of handling xml file:
Performing operations on xml file and saving changes, which includes creating xml elements(tags), assigning values,
appending them to xml root element,...
(for this we have to include namespace 'using System.Xml')

Example to insert a record:

XmlDocument doc = new XmlDocument();
doc.Load(openFileDialog1.FileName);

XmlElement root = doc.CreateElement("student")
XmlElement sno = doc.CreateElement("sno");
XmlElement sname = doc.CreateElement("sname");
XmlElement course = doc.CreateElement("course");
XmlElement fee = doc.CreateElement("fee");
XmlElement photo = doc.CreateElement("photo");

sno.InnerText = sno_txtbx.Text;
sname.InnerText = sname_txtbx.Text;
course.InnerText = course_txtbx.Text;
fee.InnerText = fee_txtbx.Text;

phototask();//refer 'Code' for phototask()
photo.InnerText == pname;

root.AppendChild(sno);
root.AppendChild(sname);
root.AppendChild(course);
root.AppendChild(fee);
root.AppendChild(photo);

doc.DocumentElement.AppendChild(root);
doc.Save(fdir);
MessageBox.Show("record inserted");

For Deleting

XmlDocument doc2 = new XmlDocument();
   doc2.Load(@"C:\Documents and Settings\rajshree\Desktop\Library.xml");
   XmlNode nodeList = doc2.SelectSingleNode("/catalog/book[@id='" + ddBookId.SelectedItem.Text + "']");
   doc2.DocumentElement.RemoveChild(nodeList);
   doc2.Save(@"C:\Documents and Settings\rajshree\Desktop\Library.xml");
    lblerror.Text = "Deleted Successfully";


For Updating

XmlDocument doc1 = new XmlDocument();
   doc1.Load(@"C:\Documents and Settings\rajshree\Desktop\Library.xml");
   XmlNodeList nodeList = doc1.SelectNodes("/catalog/book[@id='" + ddBookId.SelectedItem.Text + "']");
   nodeList[0].ChildNodes[4].InnerText = txtpub.Text;

    doc1.Save(@"C:\Documents and Settings\rajshree\Desktop\Library.xml");
    lblerror.Visible = true;
    lblerror.Text = "Updated Successfully";



Linq To Object
namespace FinalExam
{
    public partial class Linqtoobject : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<person> per = new List<person>();
            person p = new person();
            p.name = "sandip";
            p.designation = "manager";
            p.salary = 10000;
            per.Add(p);

               p = new person { name = "Naimish", designation = "manager", salary = 8000 };
               per.Add(p);

               var data=from db in per
                        select db;

               GridView1.DataSource = data;
               GridView1.DataBind();

               List<student> std = new List<student>();
               student stud = new student("sandip", 7, "a");
               std.Add(stud);

               var data1 = from db in std
                           select db;

               GridView1.DataSource = data1;
               GridView1.DataBind();
        }
    }
    class person
    {
            public string name { get; set; }
            public string designation { get; set; }
            public int salary{get;set;}
    }

    class student
    {
        public string name { get; set; }
        public int sem { get; set; }
        public string div { get; set; }

         public student(string Name, int Sem, string Div)
         {
            name = Name;
            sem = Sem;
            div = Div;
        }
    }
}

Linq To Sql

            var grpqry = from db in ddc.Emps
                          group db by db.emp_name into g
                          select new { FirstLatter = g.Key, words = g };

            var grpqry1 = from db in ddc.Emps
                         group db by db.emp_name into g
                         select new { name = g.Key };

            var grpqry2 = from db in ddc.Emps
                          where db.emp_id>=10
                          group db by db.emp_id into sandip
                          select new { id = sandip.Key };

            var grpqry3 = from db in ddc.Emps
                          where db.emp_salary == "100000"
                          group db by db.emp_salary into sandip
                          select new { salary = sandip.Key };

            var whereqry1 = from db in ddc.Employees
                            where db.Department == "it" & db.City=="jaipur"
                            select db.EmployeeName;

            var whereqry2 = from db in ddc.Employees
                            where db.Department == "it" | db.City == "jaipur"
                            select db.EmployeeName;

            var l_whereqry3 = ddc.Employees
                            .Select(dept => dept.EmployeeName);

            var l_whereqry4 = ddc.Employees
                            .Where(id => id.EmployeeID == 4)
                            .Select(dept => dept.EmployeeName);

            var l_orderqry = ddc.Employees
                            .OrderBy(id=>id.EmployeeName)
                            .Select(id=>id.EmployeeName);

            var l_orderqry1 = ddc.Employees
                            .OrderBy(city => city.EmployeeName)
                            .Where(ct => ct.City == "surat")
                            .Select(id => id);

            var l_qry1 = ddc.Employees
                        .Where(ct => ct.City == "surat")
                        .Select(id => id);

            var l_groupqry = ddc.Employees.GroupBy(name => name.Department)
                            .Select(emp => new{ Department = emp.Key });

            var l_grouporderby = ddc.Employees
                                .OrderBy(city => city.City)
                                .GroupBy(ct => ct.City)
                                .Select(Emp => Emp.Key);

            var l_grouporderby1 = ddc.Employees
                                .OrderBy(city => city.City)
                                .GroupBy(ct => ct.City)
                                .Select(Emp => new { City = Emp.Key });
            var l_count = ddc.Employees
                        .Select(Emp => Emp )
                        .Count();

            var l_sum = ddc.Employees
                        .Select(emp => emp.EmployeeID)
                        .Sum();



            Response.Write(l_sum);
            GridView1.DataSource = l_grouporderby1;
            GridView1.DataBind();

Linq to Xml

using System.Xml.Linq;
using System.IO;
using System.Xml;

namespace FinalExam
{
    public partial class Linqtoxml : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            XDocument document = XDocument.Load(@"E:\FinalExam\FinalExam\XMLFile1.xml");
            XElement root = document.Root;
            var data = from db in root.Elements("student")
                       select db;

            GridView1.DataSource = data;
            GridView1.DataBind();

            foreach (XElement xEle1 in data)
            {
                Response.Write(xEle1);
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            XNamespace empNM = "urn:lst-emp:emp";
            XDocument xDoc = XDocument.Load(@"E:\FinalExam\FinalExam\XMLFile1.xml");
            xDoc = new XDocument(
                        new XDeclaration("1.0", "UTF-16", null),
                        new XElement(empNM + "students",
                            new XElement("student",
                                new XComment("Only 3 elements for demo purposes"),
                                new XElement("name", "sandip1111111111"),
                                new XElement("sem", "7"),
                                new XElement("d", "a")
                                )));

            StringWriter sw = new StringWriter();

        }
    }
    class Student
    {
        public string name { get; set; }
        public int sem { get; set; }
        public string div { get; set; }
    }
}

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:19
posted:11/27/2012
language:English
pages:25