What are Object’s in Programming

8 11 2009

The very basis of Object Programming relies on the concepts of Objects.

So what are objects? and how do they the working of OOP’s.

Before we start understanding object’s under OOP’s lets us first try and understand objects from real world. Let us consider a table lamp, which is lying on our desk. The lamp has certain utility and functions that it performs. The functions of the object and its characteristics define the a lamp. For example the lamp can be either put on or off and the lamp gives light or it can be off so it does not give light. These behaviour of the object can be classified into behaviour and state. The state of a lamp can either be on or off and the behaviour can be turning on or turning off.

Similarly all the other objects that we see in real world have these to parameters to define and distinguish them from each other.

In programming concepts objects exhibit the same parameters and are used by other objects to achieve some task. So that means each programming object has a behaviour and state.

State of objects in programming are called fields or variables and behaviour are called methods or functions. So we use variables to store characteristics of a object and the functions to perform so action on those characteristics.

Let’s understand this with the help of an example.

Say for example we are supposed to build an application to capture employee information and process his wages based on the number of days that he has worked.

So we will create an employee class which will have state or variables like

  • name
  • age
  • no of days worked
  • daily wage rate
  • payable wages,  etc.

Now using this information that we have provided we will write a behaviour or a function which will calculate his wage rate.

This function will basically multiply no of days worked with daily wage rate and return the computed figure as payable wages.

So using the state of the object we perform certain actions on the same to achieve our task.

But why do we need to use objects in our programs?

  • Modularity: An object can be written independent of other objects and can be used by other objects.  So we can have one object called as employee and another object called as job. Job object can reference the employee object to perform certain tasks. . Once created, an object can be easily passed around inside the system.
  • Information – Hiding: Using methods we can hide the structure and details of the object. That means an calling object just needs to know the function name and the values to be passed. What happens inside the object has got no business with calling object. On successful completion the object can return some value to the calling object.
  • Code Re-use: Once an object has been created it can be reused in the same project or other projects needing the same functionality. Saves time and resources.
  • Debugging and Pluggability: If there is an object that is creating problem in your program, just remove it and replace with another object. It is easier to debug modular structures as we will be testing and checking unit by unit instead of checking the whole code. It helps to narrow to the problem source and faster ramifications.

I will try and cover more on the uses of objects in my coming few articles, where you will learn the real power and use of objects in real life programming.

Some of this knowledge that I have presented comes from sun.com

Will follow up with more relevant articles.





How do i get the ID of last Inserted Record

7 11 2009

Many of us face a problem with programming in .NET and SQL server that when a new record is inserted into the table with a primary key that is auto generated/ identity seed. How do we find out the auto generated ID of the last inserted record?

Using Data Adapter is a common practise and the architecture of ADO.Net which takes the Data off line and refreshes only when we perform a requery or update on the data adapter. Since newly inserted records will not have and auto-generated identity key, which is fetched only after an update is executed on the data set.

On a multi-user environment there are many users accessing the same database table and adding information at the same time. So when an insert is executed by us and there are very high likely chances that there are other users also who are executing an insert on the database. So when our data adapter is refreshed the requery will return all the records from the table which includes your newly added record and the records added by other users.

If we use simple logic and run to the last record in the data table to find the value of primary key, there are chances that this record may not be the one that we inserted and may lead to wrong information being fetched.

So how do I get the value of my primary key which is an identity seed?

Well its very simple T-SQL provides a command @@IDENTITY that returns the value of identity which was last generated by an insert command.

So after you have executed your data adapter update statement, just execute this set of statement to get the identity that was generated.

C# code

 

SqlCommand cmd = new SqlCommand(“SELECT @@IDENTITY”, SqlConn);
Id = int.Parse(cmd.ExecuteScalar().ToString());

The variable Id will contain the value of last generated identity seed.

@@IDENTITY returns value for each connection so you need worry about fetching the value of someone else’s insert statement.

Another T-SQL command SCOPE_IDENTITY() returns the last generated identity value for a current scope. I will cover this more in detail in my next article.

 





Devx ASP Grid Problem

3 11 2009

One of my ex-colleague sent me this request

Hi

I have a problem with DevExpress.Web.AspxGridView 9.2.5 used in our website

Following is the scenario where I am having strange behaviour of the grid while updating grid row

Machine 1 Machine2

Name: SERVER1 SERVER2

OS : Windows 2003 SP2 Windows 2003 SP2

Web Server: IIS 6 IIS 6

SQL Server: SQL Server Express 2005 SQL Server Express 2005

SQL Server Instance: SERVER1\SQLEXPRESS SERVER1\SQLEXPRESS

Database Name: MyDB1 MyDB1 (Copied from Server1)

Start Website installed in Server1 from same machine

1. Connect to SERVER1\SQLEXPRESS database MyDB1, insert update and edit update of the grid works fine.

 

2. Connect to SERVER2\SQLEXPRESS database MyDB1 ( it’s an exact copy of MyDB1 in Server 1), insert update or edit update of grid hangs

Start Website installed in Server2 from same machine

1. Connect to SERVER1\SQLEXPRESS database MyDB1, insert update and edit update of the grid works fine.

2. Connect to SERVER2\SQLEXPRESS database MyDB1 , insert update or edit update of grid hangs

It reveals that the problem is with updating data into SERVER2\SQLEXPRESS from the grid even if the database used in this SQLServer is an exact copy from SERVER1\SQLEXPRESS

 

I tried my best to compare the SQLServer Installations of both machines and all looks fine.

You help asap will be highly appreciated

Regards

 

Jos

 

This is how he solved it

 

Hi Zaheed

Thanks for the reply ,  Finally nailed it. It was due to the Language settings in one SQL Server (as US English) which in turn accepts date format in mm/dd/yyyy for stored procedure parameters. One of our .NET stored procedure call was passing  dd/mm/yyyy format date thus causing a  failure at the backend. Unfortunately this error didn’t propagate to the frontend  Xtab grid and grid seems like hanged. I changed the stored procedure input parameter date formatting and implemented some error handlings for ASPxGridView and its now working fine. Thank you so much for your help. Hope your work and project going fine.  Will catch up with you later

 

Regards

Jos





Sample programmers technical test

1 11 2009

TEST for Junior Programmer

Design a Windows based application using .Net and SQL Server. The following functionality has to be achieved in this application.

A company dealing in software development pays its employees on hourly basis for the work that they do. If the employee has put in 10 hours per day he will be paid for the 10 hours. The payments are made on weekly basis. Employees have different rates depending on their designation in the organization.

Develop a solution that will help you capture this information and process weekly pay sheets for individual employee. There must be a form to capture how many hours for a particular date that an employee has worked.

Tasks

  1. Design / Create Database
  2. Develop Windows Form Application




How to avoid the spam filter? Did he get my mail?

1 11 2009

Why has he not replied to my mail?

Did he receive my mail?

There is always some uncertainty with the emails that we send as we are not sure that has the receiver, received our mail.

Spam filter’s which has been a boon for many of us can sometimes act as a nuisance for legitimate mails and put them into spam folder only because it does not meet the required standards of a legitimate mail. Well these intelligent spam filters can sometimes act dumb by putting our legitimate mails into spam folder and keeping us ever guessing, why that person has not replied back.

 

Here are some tips that you should take care when sending mails:

Request the recipient to add your email address to his address book or the safe sender list. Some silly spam filter’s will not accept mails from addressed that are in the safe sender list.

Be diligent while crafting your mail. Avoid using words like ‘Free’, ‘Get money’, ‘Guarantee’ etc in your subject line. Making your mail look like, sales pitch also acts as deterrent. Avoid using words that sounds like you are trying hard to sell your product or services.

However urgent your mail would be, avoid using these words – “Urgent”, “Important” also other most commonly filtered words are “Free”", “New car”, “Loan”, “Insurance”, “investment”. Try to use some alternative words. The sentences should be short. Don’t send e-mails containing libelous, defamatory, offensive remarks. Make sure not to write in “CAPITALS” and attach unnecessary files.

Well for most of us who are very official in our approach, don’t use the word ‘DEAR’ to address someone.

SUBJECT LINE IN CAPITAL may not get your recipients attention but will surely get noticed by the spam filter and increase your spam score.  Spam score is a formula to evaluate whether an e-mail is a spam or not. A score (by default) of 5.0 is enough to mark your email as “spam.” The rules used in assigning spam scores change and update frequently.

Other factors like HTML, hyperlinks, background color, large fonts etc can also increase your chances of getting a high spam score. Text format is still the best way of sending mails.

 

If you have suggestions, please leave a comment……





What is COALESCE

31 10 2009

Ever had problems with nulls in your database? Null values sometime can play havoc and lead to eronous results or totaly wrong output.

We can use where conditions like is not null to filter out null values in our output. But what about situations where you have to do calculations involving multiple fields and on each record either one of the field is blank and other have values. The where condition will fail to work here because if even one of the field is found to be null the whole record will be ignored.

COALESCE helps you work around this problem. If you want that if value of field 1 is not null than a certain calculation should be done and so on and so forth for other columns.

The following example will make it more clear on how COALESCE works. I have picked this example from MSDN

SET NOCOUNT ON;
GO
USE tempdb;
IF OBJECT_ID('dbo.wages') IS NOT NULL
    DROP TABLE wages;
GO
CREATE TABLE dbo.wages
(
    emp_id        tinyint   identity,
    hourly_wage   decimal   NULL,
    salary        decimal   NULL,
    commission    decimal   NULL,
    num_sales     tinyint   NULL
);
GO
INSERT dbo.wages (hourly_wage, salary, commission, num_sales)
VALUES
    (10.00, NULL, NULL, NULL),
    (20.00, NULL, NULL, NULL),
    (30.00, NULL, NULL, NULL),
    (40.00, NULL, NULL, NULL),
    (NULL, 10000.00, NULL, NULL),
    (NULL, 20000.00, NULL, NULL),
    (NULL, 30000.00, NULL, NULL),
    (NULL, 40000.00, NULL, NULL),
    (NULL, NULL, 15000, 3),
    (NULL, NULL, 25000, 2),
    (NULL, NULL, 20000, 6),
    (NULL, NULL, 14000, 4);
GO
SET NOCOUNT OFF;
GO
SELECT CAST(COALESCE(hourly_wage * 40 * 52,
   salary,
   commission * num_sales) AS money) AS 'Total Salary'
FROM dbo.wages
ORDER BY 'Total Salary';
GO

Here is the result set.

Total Salary

------------

20800.0000

41600.0000

62400.0000

83200.0000

10000.0000

20000.0000

30000.0000

40000.0000

45000.0000

50000.0000

120000.0000

56000.0000

(12 row(s) affected)

As you can see from the above example COALESCE takes the first occurence of not null value from amongst it agurements.

For further reading or more info on this command you can refer to MSDN on the following link

http://msdn.microsoft.com/en-us/library/ms190349.aspx





Connect to SQL Server on Port other than 1433

31 10 2009

If you want to connect to SQL server programmatically which is running on a port other than 1433, your connection string should look something like this.

cst = “Provider=SQLOLEDB;” & _
“Data Source=<x.x.x.x>,<port number>;” & _
“Initial Catalog=<dbname>;” & _
“Network=DBMSSOCN;” & _
“User Id=<uid>;” & _
“Password=<pwd>”

In my next article i will try and post connection strings for different databases engines.

 

 





Find list of SQL Servers in network

31 10 2009

This code come straight from another current posting, I take no credit -

To enumerate all network-visible SQL servers using SQL-DMO objects,
create a
new standard EXE project and add a reference to sqldmo.rll. This file
can be
found in \Binn\Resources\1033\sqldmo.rll under the SqlServer70
directory.
Now add this code and declaration in your form’s code:

Private Function GetAllSqlServerCollection(colSqlServers As Collection)
As
Boolean
Dim intIndex As Integer
Dim oApplication As SQLDMO.Application
Dim oNameList As SQLDMO.NameList

Set oApplication = New Application
With oApplication
Set oNameList = .ListAvailableSQLServers
With oNameList
For intIndex = 1 To .Count
colSqlServers.Add (oNameList.Item(intIndex))
Next
End With
End With
Set oApplication = Nothing
GetAllSqlServerCollection = True
End Function

This code quickly fetches a list of SQL servers and can be put inside a
combo box’s drop-down event to always get a refreshed list of SQL
servers on
your form.





Find list of open ports on your machine

31 10 2009

For those that may not know it, you can go to a DOS box (command prompt) and type in NETSTAT to list all the connections and TCP/IP ports used.  If you type “NETSTAT /?” it will give you a list of options.  Most of the time I used “NETSTAT -A -N”, to list all ports in use or that are listening along with using the actual port number in the list instead of names.

This can be very useful at times to see just what ports you have open on your system and which ones are in use.





Problem with DevEx XTRAGRID

30 10 2009

I am amazed with the things that we can achieve with the DevEx XtraGrid control in a .NET application. But some silly and small bugs can eat in a lot of your time because you just cannot find where the error is.

This is one of the most silliest errors that I have come across on a control’s property box.

The XtraGrid control allows you to specify a fieldname from the binded datasource that needs to assigned to a column in the grid.

I was surprised to find out that the fieldname to be specified in the grid was case sensitive.  So for example the field in your select statement is in lower case than in the grid also you will have to specify the fieldname in the same case.

Funny? yeah and that too with VB.NET

:)