How to easily learn various programming languages

Introduction

   it is the fact that there are diversity of programming languages in the pool of technology which are used for the sake of generic purposes. For example, the languages of Microsoft Company are VB.NET,C#,C++.NET,F#,A++. You can see more other programming via the link http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html. The question is how to study languages? Generally, from my experiences, I personally have found out that most of students and developers are likely to be hard to move from one language to other languages. Why? and how to solve it? the article will explore the causes and my own solutions.

Root Causes

   The first primary cause is that they do not understand the general concept of programming. They do not understand the variable scope in general, primitive data type, array and so on. this lead to confusable ideas.

   The second cause is data structure and Math. The lack of knowledge in data structure make them hard to study programming because it provides them with general concepts of solving problem effectively and efficiently. Further Math is vital. For instance, if you want to write a small program to calculate the value of N!, you need to know what the N! is.

Solutions

 There are two possible solutions as the following:

         – You should study a programming language clearly. it is not necessary that you need to C or C++ but it is better if you can start with C or C++. You should clearly understand Data Type, Variable Scopes, Array, Structure, Pointer, Function, Sub Routine, Classes, Generic,File IO..

          – Make comparison between the first one and the next programming. it means that you compare the first programming concept to the new one. For example, You know VB.NET and you want to learn JAVA. when you start java, you should ask yourself how to declare variable in java, how java scopse these variables, how java write data to file and database. The concepts are the same. the only differences are Syntax, Library, and programming Structure.

Conclusion

   In short, To learn various programming, you should understand the general ideas of a programming and compare those concept in various programming.  Moreover, as a programmer, you need to be patient because it is the fact that you will be stress when you cannot solve problem.

Generic File Read/Write with BinaryReader/BinaryWriter in C#

Background

    It is the fact that Generic provides programmer with concepts of generalization. Let say that programmer can write a program or library for general datatype. For precise example, If you want to swap int,string,single,float and so on, you can write functions for each datatype. The question is that if there are 100 datatypes, we need to write 100 functions. that is not acceptable solution. To deal with the situation, Generic takes place. With Generic, programmer can write only one swap function to apply all datatypes.

    By the way, We can read and write all datatypes to file with particular file reader and writer. it is supposed that if we have a generic list of object ( it could be product, student, rectangle…), we want to write all objects of the list to file. Is it possible to build a framework to deal with the problem. The article is aimed to explore generic file read/write with BinaryReader/BinaryWriter  in C#. it is just a tiny sample but it is viral.

Process

   There are Two interfaces(IObjectBinaryFile,IExportable) and a generic class (FileOperation) as the following picture. T is generic having constraint that T has to implement interface IExportable and IObjectBinaryFile. IObjectBinary is the interface for reading and writing operation and IExportable is for exporting content of generic list to CVS file( Comma Seperated Values).

Class Diagram

Class Diagram

code snap-sot

code snap-sot

the following picture is the code snip-sot.

Codes to Read and Write:


public Boolean ReadFromFile() {
 try
 {
 if (!File.Exists(m_filename)) {
 MessageBox.Show("File is not found!", "File Existence!");
 return false;
 }

FileStream fs = new FileStream(m_filename, FileMode.OpenOrCreate,
 FileAccess.ReadWrite);
 BinaryReader Reader = new BinaryReader(fs);
 m_objList = new List<T>();
 T obj;

while(Reader.PeekChar()!=-1){
 obj = new T();
 obj.ReadFromStream(Reader);
 m_objList.Add(obj);
 }
 Reader.Close();
 fs.Close();
 return true;
 }
 catch (Exception ex) {
 return false;
 }
 }

 

public Boolean SaveToFile() {
 try
 {
 if (System.IO.File.Exists(m_filename)) {
 // to delete file
 System.IO.File.Delete(m_filename);
 }

FileStream fs = new FileStream(m_filename, FileMode.CreateNew,
 FileAccess.ReadWrite);
 BinaryWriter Writer = new BinaryWriter(fs);
 foreach (T obj in m_objList) {
 obj.WriteToStream(Writer);
 }
 Writer.Flush();
 Writer.Close();
 fs.Close();
 return true;
 }
 catch (Exception ex) {
 return false;
 }

}
Implementation
To use the tiny library, all classes you want to save and read its contents to and from file, you have to implement the two mentioned interfaces above. Here is the example of implementation.
public class Person:IObjectBinaryFile,IExportable
 {
 public string _id;
 public int _age;
 public string _name;

public Person() {

 }
 public Person(string id, int age, string name) {
 _id = id;
 _name = name;
 _age = age;
 }

public Boolean WriteToStream(BinaryWriter writer)
 {
 try
 {
 writer.Write(_id);
 writer.Write(_age);
 writer.Write(_name);
 return true;
 }
 catch (Exception ex)
 {
 return false;
 }
 }
 public Boolean ReadFromStream(BinaryReader reader)
 {
 try
 {
 _id = reader.ReadString();
 _age = reader.ReadInt32();
 _name = reader.ReadString();
 return true;
 }
 catch (Exception ex)
 {
 return false;
 }
 }
 public string getHeader() {
 return "ID,Name,Age";
 }
 public string getContentForCSV() {
 return _id + "," + _name + "," + _age.ToString();
 }

}
List plist = new List();

plist.Add(new Person("P001", 23, "Sok"));
plist.Add(new Person("P002", 45, "Sao"));
plist.Add(new Person("P003", 56, "Sun"));

FileOperation PerOp = new FileOperation("PerList.Per");

Please download source code

Remote Procedure Call (RPC) with Zyan Framework in C# 2010

What is RPC?

     Generally, RPC is abbreviated from Remote Procedure Call. RPC is a mechanism so as to call a method of an object remotely via network. It means that Objects are hosted at the remote PC in order for clients to connect and to invoke methods of those registered objects. Please see picture below:

Structure of RPC

Structure of RPC

What is Zyan Framework?

Zyan is an open-source frame to develop the distributed application. .Net developer can host any .net class to be accessed over the network. For more detail please navigate through the site http://zyan.codeplex.com/.

Background

   It is supposed that there are two main components of the article (Server, Client). Both Server and Client have an interface called IHelloService and a class called HelloService. The interface IHelloService has a method SayHello. Please see the following code:

IHello Service

Process

1. Please download Zyan framework http://zyan.codeplex.com/releases/view/76410
2. 
Create two projects with Visual Studio 2010 (CliedntDemo, ServerDemo)
3 . Add Zyan as Reference to your projects

Note. It is supposed that you all know how to add Reference to your prject

    In ServerDemo, Please write the following codes:

ServerDemo

In ClientDemo, Please write the following codes:

ClientDemo

To run the application, you need to run Server first and then run client. You will see the “Hello Me” message on Server. It means that Method SayHello is executed remotely from client. Please download Source Here

Custom Event in VB.NET

Theoretically, Events are actions happening when an object is acted with a generic action. For example, event click occurs when user clicks a button. We all know that there are a lot of events of controls in VB.NET. With this regard, how can we create our own custom event? custom events  provide  flexibility in handling and controlling events. The article is giving details over that stuff. Three primary actions to deal with events are:

  1. Declare events
  2. Raise events
  3. Handle events 

I will prove each point as the following:

Declaring Events

You declare events within classes, structures, modules, and interfaces using the Event keyword, as in the following example:

Public Event ObjectChanged(ByVal CurrentObject As Object)

Raising Events

Object gives notification to external environment via event. To broadcast event, you use  Raise Event statement, as in the following example:

RaiseEvent ObjectChanged(_List(_curIndex))

Handling Events

Before you can make event handler usable, you must first relate it to an event by using Handles  and AddEventHandler.

The WithEvents statement and Handles clause provide a declarative way of specifying event handlers. Events raised by an object declared with WithEvents can be handled by any subroutine with a Handles clause that names this event. Although the Handles clause is the standard way of associating an event with an event handler, it is limited to associating events with event handlers at compile time.

The AddHandler and RemoveHandler statements are more flexible than the Handles clause. They allow you to dynamically connect and disconnect the events with one or more event handlers at run time, and they do not require you to declare object variables using WithEvents. However, there are some restrictions with using WithEvents.

Private WithEvents RecNavigat As Navigator(Of clsRectangle)

Please see the following full example:

Public Class clsRectangle
Protected _width As Single
Protected _length As Single
Public Event WidthChanged(ByVal oldvalue As Single)
Public Property Width() As Single
 Get
 Return _width
 End Get
 Set(ByVal value As Single)
 If value <> _width Then
 RaiseEvent WidthChanged(_width)
 _width = value
 Else
 _width = value
 End If
 End Set
End Property
Public Property Length() As Single
 Get
 Return _length
 End Get
 Set(ByVal value As Single)
 _length = value
 End Set
 End Property
Public Sub New()

End Sub
Public Sub New(ByVal w As Single, ByVal l As Single)
 _width = w
 _length = l
 End Sub
End Class
Private WithEvents R1 As New clsRectangle(12, 13)
Private Sub R1_WidthChanged(ByVal oldvalue As Single) Handles R1.WidthChanged
 MessageBox.Show(oldvalue)
End Sub
Private R2 As New clsRectangle(12, 13)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddHandler R2.WidthChanged, AddressOf R2_WidthChanged
End Sub
Private Sub R2_WidthChanged(ByVal oldv As Single)
 MessageBox.Show(oldv)
End Sub

How does Method FindAll In Generic List Work in C#?

Using FindAll Method

Basically, I hope you all are keen on using generic list. I am deeply attracted by generic list (List<T>). That why i am writing the article. By the way, There are a lot of members in List<T>  class like find,indexof,contains..etc. FindAll method is one of the members in List<T>.  FindAll Method retrieves all the elements that match the conditions defined by the specified predicate.  Predicate is a delegate. Predicate for FindAll method has the following signature:

      public delegate bool Predicate<T>( T ob )

The question is that what we should write in predicate. Logic in predicate evaluate whether the provided object ob is matched with what we want to look for or not. Technically, When List<T> find objects in list, it will automatically provide current iterated object to ob  so that we can assess the object with what we want to look for. Please the following code sample. dowload source code here

public partial class Form1 : Form
 {
 public List<Expense> Expenses = null;
 public Form1()
 {
 InitializeComponent();
 }
private void Form1_Load(object sender, EventArgs e){

Expenses = new List<Expense>();
 for (int i = 0; i <= 1000; i++) {
 Expenses.Add(new Expense(i.ToString("D4"),"Expense" +
 i.ToString("D4"),DateTime.Today.Date, new Random().Next(100)));
 }
 lstexpense.DataSource = null;
 lstexpense.DataSource = Expenses;
}
public bool SearchExpense(Expense Obj) {
 if (Obj.ExpenseOn.ToLower().Contains(txtkeyword.Text.ToLower()))
 {
 return true;
 }
 else {
 return false;
 }
 }
private void btnfind_Click(object sender, EventArgs e)
 {
 List<Expense> FoundLs = null;
 FoundLs = Expenses.FindAll(this.SearchExpense);
 lstexpense.DataSource = null;
 lstexpense.DataSource = FoundLs;
}
}

Is Structure sort-able like a class?

Technically, Structure is a composite value type. Structure may contain more than one field. Our query is that how the structure is sorted by those custom fields. The answer is yes. In fact, even structure is derived from System.Type (Not Object), structure can implement interface as a class. To sort a list of instances of  structure, an array of instances of structure, the structure need to implement interface Icomparable [(Of T)] or Icomparer [(Of T)].  Please see the following example:

Public Structure Expense
Implements IComparable

Private _id As String
Private _name As String
Private _amount As Single

Public Sub New(ByVal id As String, ByVal name As String, ByVal amount As Single)
 _id = id
 _name = name
 _amount = amount
 End Sub

Public Property ID() As String
 Get
 Return _id
 End Get
 Set(ByVal value As String)
 _id = value
 End Set
 End Property
 Public Property Name() As String
 Get
 Return _name
 End Get
 Set(ByVal value As String)
 _name = value
 End Set
 End Property
 Public Property Amount() As Single
 Get
 Return _amount
 End Get
 Set(ByVal value As Single)
 _amount = value
 End Set
 End Property

Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
 Dim exp As Expense = CType(obj, Expense)
 Return _id.CompareTo(exp._id)
 End Function
End Structure

Public Structure NameComparator
 Implements IComparer
 Private _id As String
 Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
 Dim exp1 As Expense = CType(x, Expense)
 Dim exp2 As Expense = CType(y, Expense)
 Return exp1.Name.CompareTo(exp2.Name)
 End Function
End Structure</p>
'Expensees is an array of expesne
Array.Sort(Expenses)
Array.Sort(Expenses, New NameComparator())

For more detail, please download the source code
The purposes of the project are:
– Show how to use array and Structure
– Show how to sort structure by native sort and generic field sort
– Show how handle arrow key press
– Show how to find an element in array
– Show how to use foreach with action delegation

Structure in VB.net (Part 1)

Background:
Structure is a value type. In comparison to class, a class is a reference type, yet a structure is  a value type. a value types store its value in memory. If you create a copy of a generic structure and assign it to the other instance of kind of the structure, it means that VB.NET will create another copy of structure. Structure can have constructors and implement interfaces. The .NET Framework includes many types that are structure, including many of the built-in types.

Creating a custom structure:
The way to create a structure is similar to the way of a class being created. To create a structure, you use keyword Structure.  The following example demonstrates the way of creating Expense structure.

Defining Expense Structure:


Public Structure Expense

Private _id As String
Private _name As String
Private _amount As Single

Public Sub New(ByVal id As String, ByVal name As String, ByVal amount As Single)
 _id = id
 _name = name
 _amount = amount
 End Sub

Public Property ID() As String
 Get
 Return _id
 End Get
 Set(ByVal value As String)
 _id = value
 End Set
 End Property
 Public Property Name() As String
 Get
 Return _name
 End Get
 Set(ByVal value As String)
 _name = value
 End Set
 End Property
 Public Property Amount() As Single
 Get
 Return _amount
 End Get
 Set(ByVal value As Single)
 _amount = value
 End Set
 End Property

End Structure

Using a structure

  public sub Main
    Dim exp As New Expense(t"001", "Study", 12.0)
    MessageBox.show(ex.Amount)
  End Sub


%d bloggers like this: