Tag Archives: C#

An ExpressionTree in C++

I implemented an expression tree in Object Oriented Style and that was one of the homework i had for a class at school.I hated it a lot, but finally when completed I liked it a lot, ahhhhhh felt really like i have achieved something. By the way this is a good example of polymorphism and inheritence and the concept of virtual functions and abstract base classes (if you know what I mean ? ) Many of us do all this stuff in school and keep it to school. We never design types like that at work or someone else doesnt because we dont have the time to spend in design (at least nowhere i worked people had the time to design) but oh well !!

The logic is as Follows:

An Expression Tree consists of Nodes.Nodes can be of different types (Operators , Constants , Variables). All nodes can print themselves and allow their derivative to be taken which also is a expression tree . The derivative has to be taken with respect to a variable and the expression tree can be evaluated by plugging in a value of the variable from a look up table or symbol table … 

I am posting the code (of the header file and the driver program)  just in case it interests anyone. Your comments and feedback is welcome and you can get a working copy of code if you want. Leave your email address as a comment and i will send you the copy. This is not finished as i did not implement the destructors but you will get the idea.

#include  <iostream>
#include  <map>
#include  <string>
#include  <math.h>
using  namespace  std;

/******************************************************************************************
Muhammad Asad Siddiqi
Making an Expression Tree Representation, given an expression
This files contains the prototype for following classes
-GenericNode
-VariableNode
-BinaryOperatorNode
– AdditionNode
– SubtractionNode
– MultiplicationNode
– DivisonNode
-UnaryOperatorNode
– NegateNode
– SineNode
– CosNode*******************************************************************************************/

 

class 

 PoorManSymbolTable {
private:
std::map<std::string,
double> symbolTable;
public:
PoorManSymbolTable();
void       InitializeSymbolTable();
double  getSymbolTableEntry(std::string symbol);
};

//——————————————————————————————// This class represents a Generic Node
class GenericNode
{
public:
GenericNode();
virtual double EvaluateNode() = 0;
virtual void     PrintExpression() = 0;
virtual GenericNode *Clone()= 0;
virtual GenericNode* TakeDerivative(std::string variable) = 0;
};
//—————————————————————————————–// This is the node that represents a constant like 15
class ConstantNode : public GenericNode
{
private:
double value;
public:
ConstantNode(
doubleconstant);
double EvaluateNode();
voidPrintExpression();
ConstantNode *Clone();
GenericNode* TakeDerivative(std::string variable);
};

//————————————————————————————
// This node represents a Variable like ‘X’

class VariableNode : public GenericNode
{
private:
std::string symbol;
PoorManSymbolTable symbolTable;
public:
VariableNode(std::string variable);
double  EvaluateNode();
void       PrintExpression();
VariableNode *Clone();
GenericNode* TakeDerivative(std::string variable);
};
 

//—————————————————————————————–// This is the node that represents a binary Operator ( + , – , * )

class BinaryOperatorNode : public GenericNode
{
protected:
GenericNode *left;
GenericNode *right;
public:
BinaryOperatorNode(v
oid);
BinaryOperatorNode(GenericNode *leftOperand , GenericNode *rightOperand);
GenericNode* TakeDerivative(std::string variable);
};

//—————————————————————————————–// This is the node that represents a unary Operator ( + , – , * )

class UnaryOperatorNode : public GenericNode
{
protected:
GenericNode *childNode;
public:
UnaryOperatorNode(
void);
GenericNode* TakeDerivative(std::string variable);
};

//—————————————————————————————–// This is the class that represents a + operator 

class

AdditionNode : public BinaryOperatorNode
{
public:
AdditionNode(GenericNode *leftOperand , GenericNode *rightOperand);
// realize the pure virtual function
double EvaluateNode();
void PrintExpression();
AdditionNode *Clone();
GenericNode* TakeDerivative(std::string variable);
};

//—————————————————————————————–
// This is the class that represents a – operator

class SubtractionNode : public BinaryOperatorNode
{
public:
SubtractionNode(GenericNode *leftOperand , GenericNode *rightOperand);
// realize the pure virtual function
double EvaluateNode();
void PrintExpression();
SubtractionNode *Clone();
GenericNode* TakeDerivative(std::string variable);
};

//—————————————————————————————–// This is the class that represents a * operator
class MultiplicationNode : public BinaryOperatorNode
{
public:
MultiplicationNode(GenericNode *leftOperand , GenericNode *rightOperand);
// realize the pure virtual function
double EvaluateNode();
void     PrintExpression();
MultiplicationNode *Clone();
GenericNode* TakeDerivative(std::string variable);
};
//—————————————————————————————–// This is the class that represents a / operator
class DivisonNode : public BinaryOperatorNode
{
public:
DivisonNode(GenericNode *leftOperand , GenericNode *rightOperand);
// realize the pure virtual function
double EvaluateNode();
void      PrintExpression();
DivisonNode *Clone();
GenericNode* TakeDerivative(std::string variable);
};

//—————————————————————————————–// This would be used to negate a node
// Return a negative when evaluate is called

 

class NegateNode: public UnaryOperatorNode
{
public:
NegateNode(GenericNode *argChildNode);
double EvaluateNode();
NegateNode *Clone();
void PrintExpression();
GenericNode* TakeDerivative(std::string argSymbol);
};

// ————————————————————————————–
// This would be used to create a Sine Operator in the Expression Tree
// It is a unary operation and derivative is a cos Node
class SineNode : public UnaryOperatorNode
{
public:
SineNode(GenericNode *argChildNode);
double EvaluateNode();
void     PrintExpression();
SineNode *Clone();
GenericNode* TakeDerivative(std::string argSymbol);
};

//—————————————————————————————–// This would be used to create a Cos Operator in the Expression Tree// It is a unary operation and uses negation in derivative

class CosNode : public UnaryOperatorNode
{
public:
CosNode(GenericNode *argChildNode);
double EvaluateNode();
void      PrintExpression();
CosNode *Clone();
GenericNode* TakeDerivative(std::string argSymbol);
};

// The driver program

int

_tmain(int argc, _TCHAR* argv[])
{
GenericNode *objGenericNode , *cloneTest , *derivativeResult;
ConstantNode *var1 =
new ConstantNode(45);
ConstantNode *var2 =
new ConstantNode (25);
VariableNode *var3 =
new VariableNode(“Xray”);
VariableNode *var4 =
new VariableNode(“Yellow”);
objGenericNode =
new MultiplicationNode(new AdditionNode(var3,var4),new CosNode(var2));
cloneTest = objGenericNode->Clone();
cloneTest->PrintExpression();
cout << endl <<
“Printing Derivative of Expression Tree … “ << endl;
derivativeResult = cloneTest->TakeDerivative(
“Xray”);
derivativeResult->PrintExpression();
return 0;
}

Notely: This is not about parsing an expression by putting it on 2 stacks using Infix or Postfix notation . This is an implementation of an expression tree where the structure of the tree is known 🙂 . I could not post the implementation but would be provided on request .

3 Comments

Filed under 1

ADO.Net Explained step by Step

In this tutorial I would be talking about integrating databases in your .Net Applications specifically C# applications. ADO.Net is a .Net framework’s library which is essentially the same for ASP.Net for web development and other desktop applications using C#.Net or VB.Net. In my experience the database that was used most frequently was Ms-SQL Server, off course because both are Microsoft products. .Net seems to integrate with SQL Server very easily and gives better performance.  (ADO.Net provides a Namespace specifically for SQL Server which might result in better performance with SQL Server. It is prescribed to use System.Data.SqlClient when using SQL Server as your back end instead of System.Data.OLEDB)  Having said that .Net can connect to all the major databases systems. The ones I have worked with include Oracle, Sybase SQL Anywhere, MySQL and MS-Access. For the sake of discussion I would be connecting to SQL Server Database here to show how to connect to databases using ADO.Net and do the routine operations.In many books I have seen hard coding of ADO.Net objects and configuring the data sources and some properties of ADO.Net objects which pisses me off. Simply ask yourself the question How are you going to deploy such software? Is it easy to replicate your development environment on the Target client machine? NO !! Not at all!! It’s a nightmare. So setting all the properties in code and all the configurations in a configuration file is the mostly used conventional way of doing things.

Prerequisites for this are some knowledge of C# and I would assume that you have a DBMS available that you wish to use for your practice or running sample code against.

Connecting to Database:
The easiest way to ensure database connection is through a UDL (universal data link) file. Simply create a new text file on your desktop, open it and from the file menu choose the “Save As” Option. In the “Save As” dialogue for file type select “All files” and for file name specify “abc.udl” and save the file. When you close the file you should have a new file called abc.udl. UDL FILES are a Microsoft proprietary file format that is used to configure data sources.

Simply enter your Database info and select the “Test Connection” Button. Once you see the message box that says “Test Connection Succeeded” close the dialogue by clicking “OK” and close the “Data Link File”. Open the file with notepad or any text editor and the third line in the file is the connection string.

 An Alternative approach to connection:

If the above mentioned process sounded too complicated which it is not the following connection strings can be used:

 For SQL Server use: 
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

 For MS-Access use:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccess2007file.accdb;Persist Security Info=False;

 For Oracle use:
Provider=msdaora;Data Source=MyOracleDB;User Id=myUsername;Password=myPassword; 

 For MySQL use
Provider=MySQLProv;Data Source=mydb;User Id=myUsername;Password=myPassword; 

The first step to talk to databases is to include a reference to ADO.Net library in your code. You don’t need to do it explicitly. Simply use the following statements in the beginning of your code.

 using System.Data;
using System.Data.OleDb; 

Once you have decided what database you want to connect and what connection string you have to use then your C# code starts. I would make a small method that returns an instance of System.Data.Oledb.OLEDBConnection if a successful connection is established else returns a null. 

/// <summary>/// Open the Database Connection/// There should be an entry for “Database” in the app.config
/// </summary>///
<returns></returns>
public System.Data.OleDb.OleDbConnection OpenConnection()
{
    OleDbConnection conn;
    string connectionString = ConfigurationSettings.AppSettings[“Database”];
    try
       {
           conn = new OleDbConnection(connectionString);
           conn.Open();
           return conn; 
     
}
    catch (Exception ex)
    {
        return null;
    }           

 }

 Executing an SQL Statement:Whenever you are designing or developing a database centric application, you have to perform database operations ( Select , Insert , Delete , Update) from various places within your application. Here we would discuss about the most common scenarios like there is a dropdown list from where the user selects one or more items. How to populate the Combo box? . We want to show the user search results in a datagrid or a datagridView  in a windows forms or a web form. ? We want to add new records in the database How to do it ? Below you will find answers to all such questions. For the sake of discussion let us consider we have a table in our database called Student and the columns/attributes of the table are Name,ID,Date_Of_Birth,Address,Email , Phone and SSN. I will show you how to manipulate the table from our application using ADO objects and give you some example code to play around. 

Executing a Select Statement for a dropdown list:
 Suppose you have a form where you want to update the students record.You have a dropdown where you will display all the SSN of the existing student. When the user selects the SSN the form gets filled automatically by selected students information. The user can then make changes and click a button and the changes are saved to the database. 

OK, the easiest way to load a combo box or a drop down list is by using an OLEDBDataReader object. The method with the code is shown below:

 public OleDbDataReader ExecuteDataReader(string query)
{
     try 
       
{
 
    
         OleDbDataReader reader;
              OleDbConnection conn = OpenConnection();
              OleDbCommand cmd = new OleDbCommand(query, conn);
              reader = cmd.ExecuteReader();
              return reader;
        } 
      
catch (Exception ex)
 
      
{
              return null;
        }
} 
You can call the method , get the data reader and then loop through all the items this would be something like on the form_load event of your form: // This is how you call the ExecuteDataReader Method
OleDbDataReader dr;
dr = ExecuteDataReader(“Select SSN from student”);
cmbStudents.Items.Clear();        
while (dr.Read())
{
  comboBox1.Items.Add(dr[0].ToString().ToString());
 
Executing a Select Statement to show in a datagrid or DataGridView:
The process of showing some rows of the database on a datagrid or a datagridview is essentially the same process with slightly different objects and the ways you use them.I am really pretty much against hardcoding stuff in the datagrid , the conventions you find in your first C# Book probably.I learned the fact, the hard way and believe me its no good at all. Probably good to make u understand what are the properties and what objects are closely connected or work together in the architecture.Always try to set the properties from your code instead of the designer view when it comes to ADO.Net objects like DataSet,DataReader,DataAdapter,DataGrid,Connection,Command e.t.c. Whenever you want to use Datagrids or DataGridView , the essential property is the “datasource”.This requires an instance of the dataset which has the results of the query passed in. The essential ADO.Net objects here are DataSet,DataAdapter and the DataGridView itself and that is it !!Following is the example of how to use: 
/// <summary>/// Given a query executes a dataset and returns the dataset
/// Ideal when to be shown on a Grid View for searching or display
/// </summary>
/// <param name=”query”>The Select query that returns a dataset when executed</param>
/// <returns></returns>
public DataSet ExecuteDataSet(string query)
{
    DataSet ds = new DataSet();
    try
    {
        OleDbConnection conn = OpenConnection();
        OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
        da.Fill(ds);
        conn.Close();
        return ds;
    }
    catch (Exception ex)
    {
        return null;
    }
} 
This is the calling code from where this method would be called:
 DataSet ds = ExecuteDataSet(“Select * from Student”);
 
dataGridView1.DataSource = ds.Tables[0]; 
Note: You would also have to use dataGridView1.DataBind() if you are programming in ASP.Net 
Executing an SQL statement that updates a table:
Here we are not selecting any rows from the database rather we want to run an insert , delete or update sql statement so we don’t want anything back from the database.So the OLEDBCommand instance is treated in a slightly different way. Below is a sample method which might be used to execute and update a database table: 

/// <summary>
/// executes a given insert query and returns true if query is executed ok/// </summary>
/// <param name=”query”>The insert query which does not return any dataset</param>
/// <returns></returns>
public bool ExecuteInsertUpdateQuery(string query)
{
    bool toReturn = false;
    try
    {
        OleDbConnection conn = OpenConnection();
        OleDbCommand cmd = new OleDbCommand(query, conn);
    
   cmd.ExecuteNonQuery();
        toReturn = true;
        conn.Close();
        return toReturn;
    }
    catch (OleDbException dx)
    {
        throw dx;
 
   }
   catch (Exception ex)
   {
        return false;
   }
}
This method can be used as:  string insertQuery = “insert into student values(‘1’,’2’,’3’);
bool status = ExecuteInsertUpdateQuery(insertQuery); In a similar way delete and update queries can be passed in and the method would return a true or a false indicating whether the statement was executed properly or not. So this was a brief brief introduction and a short tutorial, I would say “ADO.Net Crash Course” and I think there is much more to ADO than what I showed. Keeping in mind these are the essentials which you should know if you want to enter the database applications world with Microsoft.Net.  If you make any additions to this article or simply provide feedback so I can make the required changes, or you want free consultation with your design, leave your comments as feedback.All your feedback is warmly welcomed and I would try my best to address your issues.   

5 Comments

Filed under C#

Remote Software Update Techniques ?

I have worked on various Self Service terminal applications so far . Kiosks for bill payment , Mini statement and balance inquiries and permit printing to self checkout solutions . One requirement that I always come across and I am not absolutely sure how and what would be the better way of solving it is remotely updating software . I want my exes and dlls to be updated and who does it ? Well it can be a windows service or any other application or perhaps a separate thread watching for the updates .

I have some experience with Microsft BITS and i wrote a wrapper for BITS in C# but all i could use the wrapper for was basically file transfer . The object didnt expose some of the core methodologies that Micrsoft uses to update windows or to install windows updates …..

So if you have worked with any such scenario where software can remotely update itself or u have a design in mind do feel free to discuss . I can provide the code whatever i have experimented , but i would really appreciate any ideas / logics or implementation that could help me make a better design for these kind of problems that i often run into … The Software/Configurations Remote update !! If u have the idea and not the time or patience to develope it feel free !! I will develope it for u !! 😀

If you have any experience with making installation patches without hurting the installe application . I have tried Orca editor and the msp files , thats a pain a pain in the back side …. can u think of a smarter way ? Should we write a software which does that ? If you deploy software on a regular basis i m sure you probably might have some idea for a possible work around , I am amazaed why theres nothing from microsoft , doesnt sound that complicated :$

Cheers !!

1 Comment

Filed under Software Design

Comparison Of Pragramming Languages : Have your say ??

1928994504.jpg      java_starting.jpg   cplusplus.jpg

Programming Languages come in all tastes, shapes and sizes with their pros and cons. If you are a windows/web developer you are likely to say Microsoft.Net and if you are an open source inclined (I seriously don’t know why that would be) lolz you might have other opinion. For the sake of simplicity I would discuss the non Web development (server and client side scripting) here and would add on to my discussion in the next article. In the desktop i.e. windows and dos world having worked with C++ , VC++,VB , VB.Net , Java and C#.Net my personal favorite is definitely C#.Net. Definitely its not the best.Let me elaborate it in detail. Microsoft .Net does provide what most of the developers want. An easy way to make/change a clean UI with a great set of controls , a great collection of base classes making the day to day tasks ( File Handling , Database Handling , Exception Handling , Threads and Network programming) very easy , the scalability factor on the existing API and third party controls available , the extensive documentation and working examples that can be found everywhere , isn’t it like a dream come true .

 vb.jpg

I worked with java for some while and figured that the language is really neat , and was programming in the real sense all the way. Many people do argue that C# is more like Visual Basic with more RAD features and drag and drop support. I would say “Yes” it is but what is wrong with that? After all with all the slipping deadlines and nonexistent frameworks that’s what we are looking for. RAD features with great object oriented programming model, easy to implement the design and clean backup implementation. The problem with that however are the Portability/Compatibility issues.E.g. Whenever you want to make a product for the everyday user and publish it on the internet you have to specify that the user has to install X.X version of the framework or else your product wont work . Yes it’s a huge put off for the user and that’s one thing I don’t like about the .Net technologies. I think Microsoft can make it part of windows i.e. all standard Operating Systems by Microsoft should make sure that all the releases of .Net framework available then are installed with the operating systems. That would make the life of routine application software developers extremely easy and without having to give a link for Microsoft website to download the framework it would be simply awesome. The two problems which I find difficult when working with JAVA are the UI support and the integrated development Environment. With UI support I mean there are base classes available SWING and supporting wrapper classes but “Are they really as easy to use as the C# counterparts? No they are not!! At least to me“Now the Java lovers would argue here that there are some good and super cool IDES available like JBuilder, JCreator and Eclipse and specify the fact that they are simply great to implement Software patterns with struts and installing X.XX plug-ins on your specific IDE. What happens with that is you tend to be very specific, away from the general JAVA developer and there is not a huge community to support for your specific programming or development related issues.Same is the case when you talk about JSP and beans. Configuring the web server (Web Logic in my experience) seems to be difficult in itself and there are so many formalities to it which the new developer find difficult to adopt.With that said I would still believe that java has more pros than cons and is undoubtedly more powerful than any other programming language for application software development. It is extremely powerful and with a existing framework of UI and some good utility wrappers you just can’t beat it and Java developers are “No Wannabes”!! . They mean serious business. As far as the support and help from the existing communities are concerned try to Google a specific topic or an exact working example on C# and 8 times out of 10 you find someone in a similar situation discussing the whole issue in a forum, this is highly unlikely with C/C++ or Visual C++ and Java for that matter.  Long story short I guess it’s the requirements which influence the developers or architects to opt for a particular programming language.  Factors affecting the choice are usually Client requirements, hardware interfacing, operating environment, available developer’s expertise, ease of use, development costs, maintenance costs and portability. Anyways these were my views and my opinion totally off course doesn’t make things right or wrong. So if you are an active developer I would love to have your opinion on the comparison and the things on which you might agree or not? What are your views? What is your opinion? What are some of the best technologies, programming languages, development methods or sdks you have worked on ??

4 Comments

Filed under Software Design