Sunday, 22 May 2011

Parsing an XML file

In this post we will be reading a simple xml file if you don't know what xml is then here are some links that might help:

  1.  http://www.w3schools.com/xml/xml_whatis.asp
  2. http://en.wikipedia.org/wiki/XML
  3. http://www.exforsys.com/tutorials/xml/xml-advantages.html
so for this post i preferred not to go for a window based app but for a console based app since i just wanted to display the data from the xml file into the console, so here's how it goes: 

launch Visual studio and create a console based application with the base language as c sharp give your project an appropriate name and then create the new project



and here's the image of the xml file that we will be parsing



The next step is to create a class and add a function in which we will be writing the logic to parse the xml file, but before writing the logic inside the function we must import a namespace called as:

using System.Xml;

this namespace is used to handle the xml file like one can read the xml file and the attributes that it contains or one can create a new xml file at runtime with the help of the classes inside this namespace.

The below code shows you how to read the entire structure of the XML file and display it onto the console

 
void parseXML(String xmlFileLocation)
        {
            XmlTextReader reader = new XmlTextReader(xmlFileLocation);
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        Console.Write("<" + reader.Name + ">");
                      
                        break;
                    case XmlNodeType.Text:
                        Console.Write("<" + reader.Value + ">");
                        break;
                    case XmlNodeType.EndElement:
                        Console.Write("<" + reader.Name + ">");
                        break;
                }
            }
           
        }
Code Explanation: XMLTextReader is a class present in the System.XML namespace used to parse XML files by just taking the URL of your XML file. In the switch case block what i am doing is am just checking what element it is and what value it possesses and display the data on the console with the help of the enumerator XMLNodeType. Here's the view at the final output



Now if you want just the data from the xml file then in that case just modify the above code to

 void parseXML(String xmlFileLocation)
        {
            XmlTextReader reader = new XmlTextReader(xmlFileLocation);
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Text:
                        Console.WriteLine( reader.Value);
                        break;
                }
            }

Here's the output snap

                           


I hope that this post has helped you in understanding the concept on how to parse the XML file and getting out its data.

Friday, 20 May 2011

Dialog Boxes in Dot Net

In this post we will learn how to use the dialogue box provided by the dot net framework.

What are dialogue boxes?

When  you open a word file and write some text on it and save it remember the box that appears in front of you which says SaveAs well that’s the save dialogue box, just like the save dialogue box you have some other dialogue boxes as well, try to open some previous word file of yours you see a dialogue box you select the word file and it gets opened in front of you well that’s the open dialogue box. So now in this post we will have a step by step guidance on how to open a file and save a file using the dialogue boxes and later on we will see some other dialogue boxes.

Open visual studio and create a windows based application with c sharp as the language selected give your project an appropriate name and then press ok. Now create a view which looks like the one below by dragging and dropping the tools from the tool box library



and in case you don’t see the tool box library then go to view option on the menu bar and their you will see the toolbox option.


 
Now the above view consists of a Rick text box and a menu strip, in order to insert the standard items of a menu like files, edit,tool, etc you can select the smart tag of the menu strip where you will see the option to insert the standard items of a menu bar see the below image for reference.



Open Dialog Box

From the toolbox drag and drop the open dialogue box into your project  from the dialogos template of the toolbox. The open dialog box will appear in the component tray see the image given below



Now select the files menu from the menu strip and select the open sub menu and double click it to generate the click event so now here we will be writing a code to open a file and display it in the rick text box so let’s have a look at the code part which is given below.



 Code Explanation: In the above code we open the open File dialog box with the help of the function ShowDialog of the openFileDialog class and check if the Ok button of the dialog is pressed and if it is pressed then in that case display the data of the selected file into the rich text box with the help of simple IO operation. In the IO operation I have used the StreamReader class which will take the file location to be read and display the data in the Rich text box.

If you want to specify the dialog box to open only the text files then in that case you may apply such filters to the open dialog box with the help of the filter property of the open dialog box and here’s the code to do that

openFileDialog1.Filter = "Text Files |*.txt";

Save Dialog Box:

Similarly we have the save dialog box, drag and drop the save dialog box from the dialog template into the application, the save file dialog box is same as the open file dialog box with the only one thing in difference and that’s if the open file dialog box is used to open a file then the save file dialog box is used to save a file with an appropriate name. Here's a sample code on how to use the save file dialog box


FontDialogbox:

From the name itself you can guess that this dialog box is used to set the font and again the code to display the font dialog box is same as the one for the open dialog and save dialog now lets say I want to set the font of my rich text box then to do this the code is given below I think the code is self explanatory.




Similarly their are other two dialog boxes the print dialog and the color dialog box however the implementation of the print dialog box is some what different which will be seen in the next post but the implemetation of the color dialog is the same.

I hope that this post was useful in helping you out with the dialog boxes in Dot net, any comments positive or negative are welcome as they help me to help you.

Thursday, 19 May 2011

Create Run just like windows OS

In this post we will have a look on how to create a run application using c sharp just like the windows os Run, well not exactly but just a replica of it.

Design Phase: Here’s the view at the final output so what I want you to do is create a windows based project and drag  and drop tools in order to make the view look like the one in the given figure



After creating a view just like the above I want you to double click the Ok button and generate the click event, but before we write the code I want you to import a namespace first and the name of the namespace is

using System.Diagnostics;

System.Diagnostics:  This name space is used to give you the data associated with a particular process such as the machine name on which the process is running, exit time, events etc (refer this link for more detail explanation). 

This namespace has a class called as the Process which is used to start and stop any local system process by just entering the process name with the help of its function called Start.

Now moving back to our code what we did was clicked the button on our form to generate its click event now look at the code below and add the following code inside your button click as well so here’s how it looks

 

Code Explanation: From the above explanation of the namespace I said it has a class called as Process and it has a method called as start which will accept the process name as string and start the process typed by the user and on the hit of the Ok button and the said process will be executed.
On the Hit of the cancel button the application will just clear the text field that's all nothing much.



In the below pic i have given the output for this application by typing winword which is a command to open the Microsoft office.



and now after pressing the Ok button the Microsoft word app will be triggered and in case your system does not have word installed then in that case i would suggest using a try catch block to handle the exception thrown by the Process class.



i hope this post was helpful to you in some way or the other, do comment if you like positive or negative comments are always welcome as they help me to help you.

SDK, IDE, API and Framework

There's always a doubt in the minds of many students that sdk, framework, IDE, API are all the same, well it's nothing like that let's have a look at the basic definitions of these different architectures:

SDK: A Software Development Kit (SDK) is a set of tools used to develop applications for a particular platform(Mac, Windows). An SDK typically contains a compiler, linker, and debugger. It may also contain libraries and documentation for APIs. SDKs also frequently include sample code and supporting technical notes or other supporting documentation to help developers. Often the SDK can be downloaded directly via internet many SDKs are provided for free.

IDE: Integrated development environment (IDE) contains certain controls and editor with the help of which designers can design the user interface and write code for each controls in the editor.

Framework: Framework are classes provided by organizations which helps the programmers to perform complex task. Let's say earlier programmers used to code for database using lengthy procedures now that was time consuming so in order to ease their work, programmers will use a framework which will provide them certain classes and function which will help them to do the database connectivity or any other part regarding database within few steps.

 
Example:COCOA TOUCH (used for making i phone apps), .net framework, Java server faces

API: Application programming interface (API) is an interface between two software with the help of which they can communicate with each other. API is software to software interface (not a user interface) here's an example of API.
When you buy movie tickets and enter your credit card details then the movie ticket website uses an API to send your information to remote application that verifies whether your information is correct or not and once the information is correct the payment is deducted from your account and tickets are issued. At a time the user is only able to see one screen in this case the movie ticket website but behind the scene their are various application working together with the help of API.

Another example of API is facebook which uses google api to communicate with your gmail account to send friend request to your friends.

OOPS Four Pillars

In this post we will see four pillars of object oriented programming (OOPS).
 
Starting from the beginning we had C programming which is procedural oriented or you can say more function oriented, you can make robust application in C, a very good example of this would be your windows operating system which is made in C. So now the question rises that when such brilliant applications can be made by using a procedural oriented language (POP) then why do we need OOP.
 
The answer that why do we need OOP is given below:
  1. In POP large programs are divided into functions, while in OOP they are divided into class whose object can be used later.
  2. POP has no access specifier (private,public,protected) while OOP has access specifier which help the programmer to have a grip on the variables which carry important data.
  3. In POP most of the function share global data now the disadvantage here is that a function may also try to update the value of the global variable and if any of the function does update the global value then in that case you are not sure about the accuracy of the result that your program will give you.
  4. In POP operator cannot be overloaded.
Before beginning with OOPS i would like to have a small discussion on classes and objects
 
Classes and objects: 
classes are the blueprint of your actual object, consider a blueprint of a building the engineer looks at the blueprint and based upon that blueprint he builds a building, the final product in this case is building which is said to be the object in programming terms, based upon one blueprint the engineer can build 10 or 20 building but the name of those buildings are different which means that we cannot give the same name to the object of our class we have to give it different names else it might create problem. Objects have states and behaviors, states means property and behavior means methods or functions.

Now coming to the four pillars of object oriented programming: 

Abstraction: It means to hide the unwanted information and giving only the relevant information.
Example: say you want to buy a car and you go to a car showroom asking the salesman to show you a business type car, the salesman shows you audi. You ask him about its price and engine type and the relevant information is provided by that salesman. This is known as abstraction means giving only relevant data to the user and not the complete data. 

Encapsulation: It means to hide the complete information from the user.

Example: As a developer you build the application and give the end product to the user /client, you give him the setup file that's it, you don't provide the user the source code, your code is encapsulated in that setup file from which the user is unaware that what code or what language you have used to code for this particular application he just wants the end product that's all. Another example would be the medical capsules.  For us it is just one particular capsule but if  remove its upper cap we can see that their are mixtures of more than one medicine in that one capsule so here too the patient is unaware of the mixtures and thinks that its just one particular capsule. 

Inheritance: This term means deriving some of the characteristic from the parent class.

Example: you are children of your parents in this case your parents are the parent class and you are the child class, and of course you must have derived some of the characteristic from your parents like your looks, hairs, attitude etc. you must also have come across people who must have said that you look like your mom or like your dad this means that you have derived looks from either your mom or dad. Besides the parent class characteristic the child class also has some of its own characteristic and behaviours. 

Polymorphism: If you divide the term "polymorphism" then you are left with two words that's poly and morphism. Poly means many and morphism means forms. It is often expressed by the phrase "one interface multiple function"

Example: Graphical user interface(GUI) where you have only one interface but at a time their are multiple functions which are working together to get your job done.
 
You can apply polymorphism to reduce the complexity within the functions. Polymorphism are of two types it can be either static or dynamic. In static the response to a function is decided at compile time while in dynamic it is decided at run time.
 
Example of static polymorphism: players of a team are decided before the match, that's something the audience already know before the match.

Example of dynamic polymorphism: In a soccer match at substitution which player will be entering the field and which player will be replaced that is know to the audience only during the play.

i hope that this post was helpful in clearing the concepts about the OOPS four Pillars.

Wednesday, 18 May 2011

The Three Keys

The three keys in dot net are as follows:
  1. CLR (Common language Runtime).
  2. CTS (Common Type Specification).
  3. CLS (Common Language Specification).
Alright now whats the big deal about them?

Well for a start your dot net system depends upon all these three components for proper execution of the code.

CLR (common language runtime): The CLR is also know as the "execution engine" of .NET. It's the CLR that manages the execution of programs. When the .NET program is compiled, the output of the compiler is not an executable file but a file that contains a special type of code called the Microsoft Intermediate Language(MSIL, now called CIL, Common Intermediate Language). This MSIL defines a set of portable instructions that are independent of any specific CPU means that the MSIL code is independent of the computer h/w and OS. It's the job of the CLR to translate this Intermediate code into a executable code when the program is executed making the program to run in any environment (but before you run such program make sure that .net framework is present in that machine else it wont work). 

This MSIL is turned into a executable code  using a Just In Time complier (JIT) and then finally you see your output so in a nutshell process goes like this:

when .NET programs is executed the compiler creates the MSIL code which is converted into native code by the JIT (JIT will be triggered by theCLR) and hence you see your output. 

Also the other advantage is that the programmers need not worry about managing the memory themselves in the code. Instead the CLR will take care of that through a process called Garbage collection. This frees the programmer to concentrate on the logic of the application instead of worrying about memory handling. 

what does MSIL really do for you? 

First of all you cannot access the MSIL code, the advantage of MSIL is that it makes your code compatible with other programming language which means that I write a program in C#.NET and compile it. The CLR will take your code and put it into this MSIL language so that other languages in the .NET group can understand it. 

Lets say you come along and want to write a VB.NET application that works with my C#.NET application. No problem. Your VB.NET application will get translated into MSIL as well and will read the MSIL from my C# application and they can work together.This is the top notch advantage of the .NET framework.Now you can have projects which have parts written in C#, VB.NET even VC++.NET and they can understand one another.

CTS (Common Type Specification): The common type system defines how types (Data Types, Interface, Pointers, classes, Delegates, etc) are declared, used, and managed in the runtime, and is also an important part of the runtime's support for cross-language integration.

CLS (Common Language Specification): CLS provides set of rules and object oriented programming model to be followed by every .net language.when a language follow these rules and object oriented programming model then only that language was treated as .net language.

The mail purpose of cls is to integrate multiple language into .net. This is a subset of the CTS which all .NET languages are expected to support. The idea is that any program which uses CLS-compliant types can interoperate with any .NET program written in any language. This interoperability is very fine-grained - for example a VB.NET class can inherit from a C# class 

i Hope that this post has helped you in understanding the these three keys of Dot net, any comments positive or negative are always welcome because they will help me in my blogging capabilities and will help me to help you.

Cross Language Integration

In this post we will have a look on how dot net supports cross language inheritance.

In some of the books i have read that dot net has a cross language inheritance support and when i was a beginner i was not really aware about this term so now after doing some research i came to know what does the term means.

Cross language means you can create or download a library in one language and use it in some other language one such example is the dot net zip library which is used for manipulating the zip files and can be used easily with any .net language but initially the dot net zip library is coded in some other language. And if the library or your code contains some error then in that case the error would be displayed or handled via try and catch block with no problem at all.

So in a nutshell a developer can make a library with any programming language of his choice and give it to his fellow developers and those guys can use this library with some other language with no problem at all not only this you can inherit the classes used in those libraries or even override some virtual methods inside that library this is the beauty of cross language inheritance and to implement this you need a reference to a component means a dll.

Example: For this post i will create a simple library in C# and use the reference of this library in the VB.NET code. First of all i will create a library to add two numbers using c sharp so in order to do this just follow the given steps:

Step 1: Type devenv in run and open dot net environment and select c sharp as the language and create a new project and in that select the class library just like the image given below

Now save the library with an appropriate name,  The code given below is of the c sharp library that i have created and it contains a simple calculator class which has the add function which will accept two number from the user and will display the final result.

namespace DotNetLibrary_Calculator
{
    public class Calculator
    {
        public void add()
        {
            int a, b;
            Console.WriteLine("Enter the first number");
            a = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter the second number");
            b = Convert.ToInt32(Console.ReadLine());
            int result = a + b;
            Console.WriteLine("The addition of " + a.ToString() + " and " + b.ToString() + " is " + result.ToString());

        }
    }
}


Step 2: Alright now we are done with the c sharp library part now its time to use this c sharp library in a vb.net project. so lets create a new vb.net project and add this c sharp library class reference to this vb.net project.


So create a vb.net console application and add the reference of the c sharp library into it here's a pic to guide you.




Now when you select add reference then you will see a pop up window which will ask you to browse for the library reference that you have created, just find the C sharp library project that you created and then traverse to the bin ->Debug->DotNetLibrary_Calculator.dll file and add this file.

Note: Here DotNetLibrary_Calculator.dll is the name of my reference library so don't get confused by that, you can see your own dll in the debug folder.




Step 3: Import this dll reference into our project and the below pic will show you that i have imported the reference and also created the object of the class calculator that was present in the c sharp library now i want you to build and run the project to see the final output.




When you run this project the final output will be somewhat like the image given below



You can even create a new class in vb.net inherit the calculator class (this is cross language inheritance that we are talking about) and use the functions of the calculator class in that class, here's a snap of that code


The output will be same as above.

i Hope that this post has helped you in understanding the concept of cross language inheritance, any comments positive or negative are always welcome because they will help me in my blogging capabilities and will help me to help you.