Feeds:
Posts
Comments

With the help of this article I want the users to have basic overview about inflation. This article does not contain much analysis, may be in future I would be able to bring some more explanation and examples. Any suggestions are most welcome.

First Question: What is Inflation?

In simple English sudden increase (price hike within less span of time) in the price of goods is called inflation. Deflation is reverse of the inflation.

Understanding inflation

 

Basic Mathematics behind Inflation:

Description/ Date 01-Jan-2011 01-May-2011
Total Money (Rupee) in Country [] 10,000 15,000
No of Goods available in country 100 100
Price of a good [] 10,000/100 = 100 15,000/100 = 150
Within 5 months cost of a good is increased by 50%. See the notes to understand the reasons for increase in total income of the country.

 

Basic causes of inflation

As a result of imbalance of below two legs inflation is caused/ increased.

Leg1: Income of a significant percentage of population is increased.

i)                    Because of 5th Pay Commission salary of Government employees is increased.

ii)                  Government has introduced several new schemes for Un employed village peoples e.g. Narega, various pension schemes etc.

iii)                Increase in software work from other countries has made the IT peoples growth very significant.

Leg2: On one hand amount of money in the country is being increased but no of goods e.g. production of food grains, clothes etc has not changed into that respect. This leg also is improved but not in proportion of leg 1.


1.    Introduction

DALC4NET is an Open Source data access layer built for Microsoft .NET projects.  This enables us accessing data from SQL Server, Oracle, MySql, MS Access, MS Excel etc data bases.

DALC4NET is developed using C#.NET.  Microsoft .NET Framework 2.0 is required to use DALC4NET.

Users are free modify the source code as per their need.

For any feedback/ suggestion you can mail the author at ak.tripathi@yahoo.com with subject line ‘DALC4NET’

Note: In order to connect with MySql database you need to have MySql connector for .NET. Which may be downloaded from the below url

http://dev.mysql.com/downloads/connector/net/

2.    Various Providers

Database Provider to be used
MS SQL Server System.Data.SqlClient
Oracle System.Data.OracleClient
MySQL MySql.Data.MySqlClient
MS Access/ MS Excel System.Data.OleDb
MS Access/ MS Excel System.Data.Odbc

3.    How to use DALC4NET?

  1. Download DALC4NET.dll from http://www.codeproject.com/dalc4net/
  2. Add reference of the DALC4NET.dll to your project
  3. Import the namespace DALC4NET (e.g. using DALC4NET;)
  4. Create instance of DBHelper class of DALC4NET library. This class facilitate us for execution of any kind of SQL Command or stored procedure.

DBHelper.cs is a singleton class and hence we will not see any constructor for DBHelper class (singleton class has private contructor). GetInstance() method can be used for creating the instance of the class. GetInstance() method has three overloads.

i. No Parameter

This instance does not require any parameter. This overload creates connection for the connection string name mentions as the default connection.

Note: For using this overload ad an appSettings key “defaultConnection” and set you appropriate connection’s name as the value for this key.  This is the most recommended overload as we need not to do any kind of code changes if we want switch over the database. E.g. Application is supposed to have three databases MS SQL Server, Oracle and MySql. Create three Connection strings into app/web.config file’s connectionString’s section say sqlCon, oracleCon, mySqlCon. If you want application to use SQL Server set value=”sqlCon” for the appSetting’s key=” defaultConnection”. In future if your client want to use oracle database then after porting the oracle database you simply need to change the defaultConnection value i.e. value = “oracleCon”

ii. Connection Name as a parameter

This overload creates instance for the connection name specified into app/web.config file.

iii. Connection String and Provider Name as parameters

This overload creates instance for the specified connection string and provider name.

4.    How Execute SQL Command/ Stored Procedures

In section 2 we created instance of the DBHelper class say _dbHelper. We can execute any Sql Command as follows

4.1   Execute SQL Command

string sqlCommand = “SELECT Count(1) FROM USERDETAILS”;

object objCont = _dbHelper.ExecuteScalar(sqlCommand);

4.2   Execute Stored Procedure with parameters

object objCont = _dbHelper.ExecuteScalar(“PROC_DALC4NET_EXECUTE_SCALAR_SINGLE_PARAM”, new DBParameter(“@FIRSTNAME”, “ashish”), CommandType.StoredProcedure);

In the similar way we may use the appropriate method and overload to execute Sql Command or stored procedure.

5.    DALC4NET Design Overview

DALC4NET is implements following design patterns Singleton, Provider and Factory design pattern.

DALC4NET has only three public classes i.e. DBHelper, DBParameter and DBParameterCollection

5.1 Singleton Design Pattern Implementation

4.1.1 DBHelper class

DBHelper is a singleton class and it has three private constructors. Appropriate constructor is called on invoking the static method GetInstance. This method first of all checks if there is any live instance of the class then that instance is returned. If instance is null (i.e. no live instance) then a new instance is created using appropriate constructor.

private static DBHelper _dbHelper = null;

public static DBHelper GetInstance()

{

if (_dbHelper == null)

_dbHelper = new DBHelper();

return _dbHelper;

}

4.1.2 AssemblyProvider class

AssemblyProvider class also is implemented as singleton as this is the class responsible for loading the appropriate assembly for the specified provider. If this class is not implemented as singleton then every time when this class is instantiated assembly is loaded, this may be costly operation for memory.

Singleton implementation is similar as above.

5.2 Provider Pattern Implementation

All the assemblies for each of the providers are maintained into Hastable data structure. There is a hashtable which contains information about assembly details of each provider.

_dbProviders Hashtable

Key Value
System.Data.SqlClient System.Data, version=2.0.0.0, culture=Neutral, PublicKeyToken=b77a5c561934e089
System.Data.OracleClient System.Data.OracleClient, version=2.0.0.0, culture=Neutral, PublicKeyToken=b77a5c561934e089
MySql.Data.MySqlClient MySql.Data, version=6.0.3.0, culture=Neutral, PublicKeyToken=c5687fc88969c44d

When GetInstance method of this class is called then above hashtable is used to know and load the appropriate assembly for the requested provider using concept of reflection.

LoadAssembly method is responsible for loading the appropriate method

private void LoadAssembly(string providerName)

{

string assemblyName =  _dbProviders[providerName].ToString();

_assemblyName = new AssemblyName(assemblyName);

_assembly = Assembly.Load(_assemblyName);

}

First of all this method gets the name of the assembly from the hashtable, then it instantiates the _assemblyName and then it loads the assembly.

6.    DALC4NET Help

Use DALC4NET tester to see how Sql Command/ Stored Procedures are executed. Here you may find the example for execution of various kind of sql command/ stored procedure execution and uses of their result.

In order to use the DALC4NET Test application

1. Download the appropriate database backup (SQL Server/ My Sql)

2. Restore the backup with name DALC4NET_DB

Now you can play around with the sample code.

Very frequently we use to hear the news like, “SENSEX or NIFTY has touched the scale of 18,000…” or “SENSEX or NIFTY is going up” or something like this…

As a layman, the first question arises in our heads that,

What does it mean by SENSEX and NIFTY?

In India there are two main stock exchanges

  1. Bombay Stock Exchange (BSE) situated in Mumbai. Its index is called SENSEX.
  2. National Stock Exchange (NSE) situated in Delhi. Its index is called NIFTY.

So, now we are aware with SENSEX and NIFTY.

In simple words SENSEX or NIFTY is nothing but a unit less quantity which determines the direction of the stock market. If SENSEX/NIFTY is increasing we may say that stock market is growing, similarly if SENSEX/NIFTY is not growing.

Note: These are simple understanding but there are lot more things to determine the direction of stock market

Now the second question comes to our mind is,

How SENSEX or NIFTY index is calculated?

In order to answer this question we will first understand the BSE index calculation i.e. SENSEX. NIFTY index calculation is nothing but the similar process with the companies listed in National Stock Exchange (NSE), New Delhi.

There are list of companies which are registered into Bombay Stock Exchange (BSE). Every morning a set of 30 companies are chosen from the companies registered with BSE. These company’s share values are used to determine the BSE index i.e. SENSEX.

30 companies selected for SENSEX calculation should satisfy following criteria

  1. Company should have a market capitalization among top 100 market capitalizations of the companies registered with BSE.
  2. Stocks of the company should have been traded (trade means buy and sell) on each and every trading day for last one year i.e. 52 weeks.
  3. Company should have been registered with BSE at least a year before.
  4. Company should have a good track record.
  5. Company should be leaders in their group.

SENSEX Calculation:

For each of the 30 companies selected above Free Float Market Capitalization is calculated and summed up.

  1. a. Calculate Free Float Market Capitalization of the 30 companies

Free Float Market Capitalization of any company is nothing but the amount required to purchase the freely floating shares of that company. Freely Floating hares are those shares which does not belongs to company’s chair person or board of directors.

Now we understand how the free float market capitalization of any company is calculated i.e.

(#No of freely floating share) X (Price of each share)

We will now sum up the free float market capitalization of all the 30 companies

FFMC for the day = Sum of FFMC of the 30 companies selected

Here, FFMC stands for Free Float Market Capitalization

  1. b. Determine SENSEX with the help of FFMC

On 1978-79 base value for BSE index was assumed as 100. Suppose on that date FFMC was  Rs 1000 corore. In order to calculate SENSEX for the next day we are supposed to calculate FFMC for that day suppose that is Rs 1100 corore


I hope now we are clear, how SENSEX (?) is calculated.

Note: Like this we started calculating SENSEX whose base value was 100 (decided in 1978-79 as base value). SENSEX value changes every movement. The latest value depends on the previous one. i.e. Latest value is put in place of Question Mark (?) and the old value is put in the place of base value 100 and FFMCs are also replaced accordingly in order to calculate the SENSEX.

Download

1.    AccountPlus Overview

AccountPlus

1.1   Introduction

Technical Details

AccountPlus is developed using Microsoft.NET technology. It uses C# as a code language. AccountPlus is specially designed and shared for the beginners and intermediate level programmers to understand, design and implement the entire SDLC (Software Development Life Cycle). Also it may be helpful to understand

  • Implementation of Data Access Layer which supports multiple databases
  • Global Logging/ Tracing using log4Net
  • Better use of .NET winform controls
  • Globalization and localization
  • Componentization of any application.
  • Use of XML
  • Design Pattern (Used in Data Access Layer)

Functional Overview

AccountPlus is an application which can be used for shared account/expense management with proper reporting and general analytics.

In order to justify the significance of AccountPlus, we should compare the traditional account management system (paper based account management) with the features of AccountPlus.

Paper Based Account Management: Many times, it happens that multiple people share their daily expenditures. To maintain all these accounts, usually we use paper to keep track of all the individual expenses.

Drawbacks of Paper Based Account Management System

  • At the end of the month, it involves a tedious calculation to find out who had expensed what, and how much amount someone is either supposed to pay or got from others.
  • Another major drawback of paper based account management system is that we won’t be able to analyze on which item our expense is increasing so that we can control the same.
  • Paper based Account Management system has some security flaws like someone can very easily alter the expenses entered by others.

Like this, there are many disadvantages of paper based account management. But with the help of AccountPlus, at every instant we are capable of analyzing the expenses and doing the proper kind of analysis to have a better control on expenditure with full security.

1.2   User Roles and their Rights

AccountPlus has two user roles,

  1. Admin : Admin is the super user for the application who is mainly responsible for
    1. Creating/ modifying the user details to access the system.
    2. Finalizing the expenses.
  2. General User: General user is the user who accesses the system very frequently. General users are responsible for,
    1. Add/ Update/ Delete the expenses. (User can’t edit or delete expense of other users)
    2. Generating and analyzing the expenses.

2.    AccountPlus Design Overview

AccountPlus application is mainly divided into three layers

  1. 1. User Interface Layer

User interface layer of account plus contains all the forms and base class to provide style to the user interface. User interface of the application interacts with Business Layer and very rarely with Data Access Layer to fulfill the request or business action made by the user. Also this layer interacts with Messaging component of the AccountPlus very frequently for displaying the messages to the user interface.

  1. 2. Business Layer

Business Layer is the core part of the application. This component contains all the business logics being used by the application. This component interacts very frequently with the Data Access Layer for writing and reading the data to or from the AccountPlus database.

  1. 3. Data Access Layer

Data Access Layer is one among the most important components of the application. This is an independent component. This layer enables the application to interact with the AccountPlus data base in an efficient manner.  Data Access Layer is independent of database i.e. it may support all kind of databases e.g. MS Access, Excel, SQL Server, MySql, Oracle and etc. This component may be as it is used for any other application also.

Also it has three more small components for Messaging, Configuration and Formatting. Following are the details of these components

Messaging

This component is used to make application scalable in terms of achieving Globalization and Localization. Current version mainly uses this component as a message repository. This helps the application in managing the various application from a single place. This holds application into a resource file.

Configuration

This component is used to for reading the application level configuration i.e. the configuration details stored into App.config file.

Formatting

This component is responsible for formatting various data types being used by the application.

3.    AccountPlus Block Diagram

Following is the block representation of various components of AccountPlus

AccountPlusBlock

  • Logger class of the AccountPlus Business Layer enables the application to do global error/ exception logging and events tracing.
  • DataSecurity class of the Business Layer helps the application for encryption and decryption of sensitive data

4.    AccountPlus Pre-Requisites

To run Account Plus, the target machine should have,

  • Microsoft .NET Framework 2.0. To download the version, click the link below:

http://www.microsoft.com/downloads/details.aspx?FamilyID=0856eacb-4362-4b0d-

8edd- aab15c5e04f5&displaylang=en

  • Acrobat Reader. To download the version, click the link below:

http://get.adobe.com/reader/

  • Any of the following database
  1. i.            MS Access
  2. ii.            SQL Server
  3. iii.            My Sql
  4. iv.            Oracle

5.    AccountPlus Installation

  • Download AccountPlus2.0.
  • Unzip the directory AccountPlus2.0.
  • Find for the directory Setup
  • Double click to run AccountPlus setup. Keep on clicking next.

Note: Do remember to enter appropriate currency in Step 4, i.e. Rs. Or $ or anything so that your expenses are represented into the same currency. By default installer configures MS Access database, however it may be customized for any database.

Step4

6.    How to Change AccountPlus Database

AccountPlus may work with any of the database for example MS Access, MySql, SQL Server and Oracle. By default installer configures MS Access database for the application however it may be changed to any database. Downloaded package contains the db scripts for MySQL and SQL Server Database.

Follow the steps below to change the database.

  1. I. Prepare the MySQL or SQL Server database by running the scripts present into the database directory of the downloaded files.
  2. II. Go to the installation directory of AccountPlus. (Usually is C:\Program Files\AccountPlus)
  3. III. Find and open the ‘AccountPlus.UI.exe.config’ file in any suitable editor.
  4. IV. Locate ‘connectionStrings’ section. There you may get the connection strings for MySQL and SQL Server with the name mySqlCon and sqlServerCon respectively. Modify the connection string attribute with suitable values i.e. Appropriate Database name, User Id, Password, Server and Port etc.
  5. V. Locate ‘appSettings’ setion in the ‘AccountPlus.UI.exe.config’ file. Modify the value of ‘defaultConnection’ with the name of the connection String modified by you in the previous step.

Note: Make sure that while changing/ adding new connection string you are using correct providerName. E.g.

Database

Provider name

MS Access providerName=”MSACCESS”
MySQL providerName=”MYSQL”
Oracle providerName=”ORACLE”
SQL Server providerName=”SQLSERVER”
OLEDB providerName=”OLEDB”
ODBC providerName=”ODBC”

7.    Working with AccountPlus

1. Login

Provide the User name and password and click on ‘Login’ button to login into the application.

If you are selecting ‘Remember me’ then for next time application will automatically populate Username and Password.

Login

Logon Information

Click on info button to know the last log on information.

LogOnInfo

2. User Management

User management i.e. adding new users and modifying user details right is reserved for the admin user role only.

2.1 Creating new user

Login to the application as an admin user role,

  1. 1. Press ‘ALT+U’ or Go to Fileà Addà User

NewUser

  1. 2. A new window would appear. Select the desired user role and enter the user details. Click on ‘Add’ button to create user.

CreateNewUser

2.2 Searching any user

Press ‘ALT+U’ or go to File –>Add–>User. Into the window opened enter any of the details and click on search button.

Note: All the fields are not mandatory you may enter any of the details to search.

2.3 Editing user information

‘ALT+U’ or go to File –>Add–>User. Select the user from the grid whose information you want to edit. Selection of any row containing user information will make the user details available to the upper area where details may be changed. Click on ‘Update’ button to save the changes.

DeleteUserInformation

2.4 De activating user

‘ALT+U’ or go to File –>Add–>User. Select the user from the grid want to deactivate. Selection of any row containing user information will make the user details available to the upper area. Uncheck the ‘Active’ check box and click on ‘Update’ button to save the changes.

2.5 Activating user

‘ALT+U’ or go to File–>Add–>User. Select the user from the grid want to activate. Check the ‘Active’ check box and click on ‘Update’ button to save the changes.

3. Item Management

Item management i.e. adding new item and modifying item details right is given to all the user roles.

3.1 Creating new Item

  1. 1. Press ‘ALT+I’ or Go to File–> Add–> Item

CreateNewItem

  1. 2. A new window would appear. Enter the item details. Click on ‘Add’ button to create new item.

NewItem

3.2 Searching an item

Press ‘ALT+I’ or go to File –>Add–>Item. Into the window opened enter any of the details and click on search button.

Note: All the fields are not mandatory you may enter any of the details to search.

3.3 Editing item details

‘ALT+U’ or go to File –>Add–>User. Select the user from the grid whose information you want to edit. Selection of any row containing user information will make the user details available to the upper area where details may be changed. Click on ‘Update’ button to save the changes.

EditItemInformation

4. Expense Management

Only general users can add, update or delete the expenses. Admin can’t enter any expense. Users can edit or delete only their own expenses not other user’s expenses but can view all the users expense.

4.1 Adding new expense

Select the item against which you want to enter the expense. Selection of item will automatically populate the expense description where as user can change the same.  Enter other information like amount and date. Click on the ‘Add’ button to save the changes.

NewExpense

Once item is added successfully, newly added expense details would appear into the expense details grid shown right side of the screen.

Note: Expense date can’t be greater than today’s date.

4.2 Editing expense details

Select the particular expense from the grid needs to be edited. Selection of any row containing expense details will make the e details available to the left side of the screen where details may be edited. Click on ‘Update’ button to save the changes.

EditExpense

4.3 Deleting expense

Select the particular expense from the grid needs to be deleted. Selection of any row containing expense details will make the details available to the left side of the screen where details may be edited or deleted. Click on ‘Delete’ button to delete the expense.

DeleteExpense

5. Reports

Reporting is the most exciting part of AccountPlus. AccountPlus has mainly three reports:

·         Expense Report

·         Monthly Report

·         Analytic Report

Reports

5.1 Expense Report

Press F4 or click on the button present on tool bar to open expense report.

Once item is added successfully, newly added expense details would appear into the expense details grid shown right side of the screen.

ExpenseReport

Expense Report gives us the information about the

  • Total expense in the tenor.
  • Number of persons sharing the expense.
  • How much is the expense for each one. (Individual Contribution)

Based on these three pieces of information, AccountPlus calculates “How much each user has paid, and how much each participant is either supposed to pay to others participants or supposed to get from other participants”.

5.2 Monthly Report

Press F5 or click on the button present on tool bar to open monthly report.

Select the Month, Year for which report needs to be generated and click on ‘Generate’ button. Apart from the expense details this report will give the information about some other important things like Finalization Date, Total Expense and Days etc.

MonthlyReports

5.3 Analytic Report

Press F6 or click on the button present on tool bar to open analytic report.

Select the Month, Year for which report needs to be generated and click on ‘Generate’ button.

AnalyticReport

Same as Monthly report, Analytic Report also has two views Individual and Monthly.

Whenever we are generating the Analytic Report for a particular Month and Year, the Analytic Engine of AccountPlus checks whether expense data exists for the previous and next month data for the selected month and year. If data exists, Analytic Report will give the trend on a particular item or user about whether the expense has increased or decreased from the previous or next month.

Example

Suppose you have selected Dec, 2007 to generate the analytic report. Now, the Analytic Engine of AccountPlus will check whether the data exists for Nov, 2007 and Jan, 2008. If the data exists, then Analytic Report will compare the expense on each item or expense by users based on the view selected (Individual or Item wise). If data for previous month does not exist then Analytic Report will compare only the selected month and the next month.

6. Finalizing expense

Only admin user role has got the rights to finalize the expenses.

In order to understand the Finalization process, we will take the example of paper based account management system. In paper based account management system, at the end of the month, all the expenses occurred needs to be summed up, to calculate the total expense for the month. Then divide the total expense by number of persons supposed to share the expense. Like this, individual contribution is calculated. Now all the members will either receive an amount by another member or pay the amount to other members based on individual contribution and amount paid by each participant.

Once this process is completed, expense sheet needs to be tear up or to be cross marked.

Finalizing the expense in AccountPlus is the same process where admin makes sure that all the users have cleared their dues i.e. each participant have received or paid their dues. After finalizing the expense, current expense details would not be displayed on the home page but the data will remain in the database for analysis and reporting purposes.

How to finalize the expense?

Login as admin.

  • Press F4 to generate the expense report.
  • Click on Finalize button.

ExpenseFinalization

Expense report provides information about total expense and the dues for the particular tenor. Pay/Get is very important information in order to clear the dues, this information gives the information among the users about who is supposed to pay and who is supposed to get.

7. Edit user profile

Press ‘Alt+P’ or go to Edit–> Profile to bring the screen where user profile can be edited.

EditProfile

How to change password?

Check the check box ‘Change Password’. Enter old password, password and confirm passwords field s and click on ‘Submit’ button to save the details.

8. Database information

DBInfo

Press ‘Alt+Shift+S’ or go to Tools–> Database to open the database information window.

DBDetails

Note:

  • Only admin user role has got rights to back up the database.
  • Current version supports backup operation for MS Access database only.

.

9. System diagnostics

Press ‘Alt+Shift+D’ or go to Tools–> Diagnostics to open the diagnostics information window where application logs and trace can be viewed.

Diagnostics

  • Select the Log or Trace radio buttons to view Log or Trace files. Double click to open the file.
  • Export button may be used to export the Log/ Trace files.

10. Version information

Press F2 or go to Help–> About to open the about dialog box.

VersionInfo

11. Report a bug or contact author

Press F3 or go to Help–> Contact Admin to open window which helps the user to post their feed back or comments to the author.

ContactAdmin

  • Select appropriate option e.g. Report Bug, Feature request etc
  • Enter the message into the message text area.
  • Click ‘Send using Outlook’ to post the message to admin using Microsoft Outlook.

In this section I will try to cover the frequently asked questions about ASP.NET Web Services and Windows Communication Foundation. Again I would apologies for the questions to not be in proper sequence. Surely I would arrange the same into sequence when this section will have some significant amount of questions.
So, we start now…
Question 1 : What is the data format used by ASP.NET Web Services for communication?
Answer : XML

Question 2 : What do you mean by SOAP?
Answer : SOAP stands for Simple Object Access Protocol.
We know that ASP.NET Web services is platform independent. i.e. Web Services may be used for cross platform communication for example communication between an ASP.NET Web site running on Windows environment and a JSP Application running on Linux environment.
This simply means that there should be a standard or some common format which is used for communication. This standard is known as SOAP.

Question 3: What is the SOAP message format?
Answer : A SOAP message mainly contains Message Header and SOAP Envelope.

Header Contains the information about the message being transmitted e.g. Message Length, Host Server and Requested Service etc.

SOAP Message Format

Question 4 : What do you mean WSDL?
Answer : WSDL Stands for Web Services Description Language.

.NET Framework 3.0 introduces new and exciting feature i.e. Windows Communication Foundation (WCF), where as earlier versions of the framework were containg ASP.NET Web Services only.

In this Post I would be mainly comparing the WCF with ASP.NET Web Service

Windows Communication Foundation (WCF) ASP.NET Web Service
WCF supports multiple bindings HTTP, WSHTTP, TCP, MSMQ. ASP.NET Web Services supports only HTTP binding.
WCF supports Atomic Transactions*. ASP.NET Web Services does not support Atomic Transactions*.
By default WCF uses SOAP for sending and receiving the messages. But WCF can support any kind of message format not only SOAP. ASP.NET Web Services can send and receive messages via the SOAP only.
The System.Runtime.Serialization.DataContract and System.Runtime.Serialization.DataMember attributes of the WCF’s System.Runtime.Serialization assembly can be added for .NET types to indicate that instances of the type are to be serialized into XML, and which particular fields or properties of the type are to be serialized. ASP.NET Web Services uses XmlSerializer to translate the XML data (Message Send or received) into .NET objects.

* Atomic Transactions
Following example describes that what does it mean by Atomic Transactions
Consider that bank A and bank B want to interact with someone’s account at the same time. Both banks want to withdraw from the account and the account has $10.00 in it. If bank A takes $7.00 and at the same time bank B tries to get $5.00, what will happen? When they start the transaction each bank believes there is $10.00 available in the account. When one of them finishes the other one will find there is not enough money to finish the transaction.
This scenario is common for computer systems and you can see it many times in memory management, IO operations and database interactions.
Atomic transactions are a way to avoid this problem. They simply lock on a transaction and do not allow any other transaction to interact with the resource. If anything fails during the Atomic transaction, everything will return to the state before the transaction started.

1.0 What Is WCF?

WCF stands for Windows Communication Foundations.

WCF combines the functionality from ASP.NET Web Services, .NET Remoting, Message Queuing and Enterprise Services.
WCFBlock
WCF provides the following features,

  1. Hosting For Component & Services
    WCF Service can be hosted in ASP.NET Runtime, a Windows Service, a COM+ Component or just a Windows form application for peer-to-peer computing.
  2. Declarative Behavior
    Similar to ASP.NET Web Services, attributes can be used for WCF Services e.g. ServiceContract(), OperationContract, DataContract and DataMember
  3. Communication Channels
    Similar to .NET Remoting WCF Services are flexible in changing the channels. WCF offers multiple channels to communicate using HTTP, TCP or an IPC channel.
  4. Security
  5. Extensibility

2.0 Understanding WCF
These days we are creating the software/application which should be capable of communication with other applications as well. Communication with other application simply means either sharing/exchanging the data or the sharing the logic.

Now, this communication may be of two kinds

  1. Over Intranet (Same Network/Platform i.e. .NET Application to .NET Application)
  2. Over Internet (Cross Platform may be ASP.NET to J2EE Application)

Suppose we are writing a .NET Software with n-tier architecture in which Win Form Client needs to communicate with Server in the same network. In such case we may go for .NET Remoting for communication between Client and Server.

Suppose, once our software mentioned above is ready, we need to expose some business logic to another J2EE application. This J2EE application is supposed to use our .NET Application’s logic over WWW. In such case we will have to write new ASP.NET Web Service to expose the logic.

Picture shown below shows the limitation of .NET Remoting
RemotingLimitation
WCF helps us to overcome this kind of Scenario, as WCF Service can be used as a .NET Remoting Component and ASP.NET Web Services as well.
WCFAdvantage
3.0 WCF in Real Time Scenario
Suppose a 7 Star hotel has contacted you for software which will help the organization to managing the hotel’s room booking say “Room Booking System”. Apart from its own features software should be capable of

  1. Communication with already running software within the hotel’s network for help desk purpose. (.NET Windows Form Application)
  2. Communication with already running software on Tourism Office for booking of rooms. (A J2EE Application supposed to access the application over WWW)

Off course we are suppose to implement the application using Microsoft.NET Technology.
Now, as we know that in order to communicate with another .NET application within same network .NET Remoting is the best option. But as per our requirement our application should be capable of interaction with another J2EE application over WWW. So we can’t go for .NET Remoting. ASP.NET web services may work fine but the correct option for now would be WCF Service.
WCFRealTime

4.0 WCF Communication Model

WCF follows Client-Server Architecture. Communication between Client and Server are established with the help of Endpoints exposed by the WCF Service. Endpoints are nothing but the locations defined by service through which message can be sent and received. Service may have multiple end points.
WCFCommunicationModel

5.0 Know some terms/ Kew words

  1. ServiceContract
    Service contracts describe the operations supported by a service, the message exchange pattern they use, and the format of each message. The service contract may be an interface or class for generating a service description. A service must implement at least one service contract. Interface or class supposed to be exposed as a service should be decorated with ServiceContractAttribute
  2. OperationContract
    Methods in the interface or class which are supposed to be exposed as a service should be decorated with OperationContractAttribute.
  3. DataContract
    Data contracts describe how a CLR type maps to schema. A data contract may be understood as a class or interface which is mapped to database and are supposed to exploit by WCF Service. This class or interface needs to be decorated with DataContract attribute.
  4. DataMember
    Properties or database table columns in the DataContract class which are supposed to be used by WCF Service should be decorated with DataMember attribute.

6.0 How to Create a Sample WCF Application with VS2008?

6.1 Create/ Manage database

Before proceeding toward the WCF Service Creation, we need to create a database say, “WCF” with one table having following schema

DatabaseSchema
Where, ReservationId is an auto generated Primary Key column.

Note: You may also restore the backup of the database given along with the sample application.

6.2 Create WCF Service

1. Open Visual Studio

2. Go to File à New à Project

3. From the left panel, select Web node of your language VB.NET/C#.NET

4. Now among the templates you will see WCF Service Application

5. Select the same (WCF Service Application)

6. Give Suitable Name (Say Practice.WCF) and Click on OK button.

WCFProjectCreation

7. Modify the connection strings section of web.config file of the WCF Service

8. By default Visual Studio would create a Service and an Interface Service1.svc and IService1.cs

9. Add new class RoomReservationRequest.cs (DataContract)

10. Import the name space System.Runtime.Serialization; if not imported

11. Create property with same data type for each columns present into the RoomReservationRequest table. Decorate RoomReservationRequest.cs class with [DataContract] attribute and each property with [DataMember].

namespace Practice.WCF

{
[DataContract]
public class RoomReservationRequest
{
[DataMember]
public int ReservationId
{
get; set;
}

[DataMember]
public int NoOfRooms
{
get; set;
}

[DataMember]
public string TypeOfRoom
{
get; set;
}

[DataMember]
public DateTime FromDate
{
get; set;
}

[DataMember]
public DateTime ToDate
{
get; set;
}

[DataMember]
public string ContactPersonName
{
get; set;
}

[DataMember]
public string ContactPersonMail
{
get; set;
}

[DataMember]
public string ContactPersonMob
{
get; set;
}

[DataMember]
public string Comments
{
get; set;
}

[DataMember]
public string Status
{
get; set;
}

 

 

 

}
}

12. Add a new class RoomReservationData.cs and write two methods say ReserveRoom and GeReservations

namespace Practice.WCF
{
internal class RoomReservationData
{
private string connectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
internal bool ReserveRoom(RoomReservationRequest roomReservationReq)
{
SqlConnection connection = GetConnection();
string sqlCommand = "INSERT INTO RoomReservationRequest(NoOfRooms, TypeOfRoom, FromDate, ToDate, ContactPersonName, " +
"ContactPersonMail, ContactPersonMob, Comments, Status) VALUES (" +
"@NoOfRooms, @TypeOfRoom, @FromDate, @ToDate, @ContactPersonName, " +
"@ContactPersonMail, @ContactPersonMob, @Comments, @Status)";
SqlCommand command = connection.CreateCommand();
command.CommandText = sqlCommand;
command.Parameters.Add("@NoOfRooms", System.Data.SqlDbType.Int);
command.Parameters.Add("@TypeOfRoom", System.Data.SqlDbType.NVarChar, 20);
command.Parameters.Add("@FromDate", System.Data.SqlDbType.DateTime );
command.Parameters.Add("@ToDate", System.Data.SqlDbType.DateTime);
command.Parameters.Add("@ContactPersonName", System.Data.SqlDbType.NVarChar, 50);
command.Parameters.Add("@ContactPersonMail", System.Data.SqlDbType.NVarChar, 50);
command.Parameters.Add("@ContactPersonMob", System.Data.SqlDbType.NVarChar, 20);
command.Parameters.Add("@Comments", System.Data.SqlDbType.NVarChar, 200);
command.Parameters.Add("@Status", System.Data.SqlDbType.NVarChar, 200);
command.Parameters["@NoOfRooms"].Value = roomReservationReq.NoOfRooms;
command.Parameters["@TypeOfRoom"].Value = roomReservationReq.TypeOfRoom;
command.Parameters["@FromDate"].Value = roomReservationReq.FromDate;
command.Parameters["@ToDate"].Value = roomReservationReq.ToDate;
command.Parameters["@ContactPersonName"].Value = roomReservationReq.ContactPersonName;
command.Parameters["@ContactPersonMail"].Value = roomReservationReq.ContactPersonMail;
command.Parameters["@ContactPersonMob"].Value = roomReservationReq.ContactPersonMob;
command.Parameters["@Comments"].Value = roomReservationReq.Comments;
command.Parameters["@Status"].Value = roomReservationReq.Status;

int rowsEffected =0;
try
{
rowsEffected = command.ExecuteNonQuery();
}
finally
{
if (connection != null)
{
connection.Close();
connection.Dispose();
}
}
return rowsEffected > 0;
}

internal RoomReservationRequest[] GetReservations(DateTime fromDate, DateTime toDate)
{
List reservedRooms = new List();
SqlConnection connection = GetConnection();
SqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT ReservationId, NoOfRooms, TypeOfRoom, FromDate" +
",ToDate, ContactPersonName, ContactPersonMail, ContactPersonMob, Comments, Status "+
"FROM RoomReservationRequest "+
"WHERE FromDate > @FromDate AND ToDate<@ToDate";

command.Parameters.Add("@FromDate", System.Data.SqlDbType.DateTime);
command.Parameters.Add("@ToDate", System.Data.SqlDbType.DateTime);
command.Parameters["@FromDate"].Value = fromDate;
command.Parameters["@ToDate"].Value = toDate;
SqlDataReader reader = null;
try
{
reader = command.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
RoomReservationRequest roomReservationRequest = new RoomReservationRequest();
roomReservationRequest.ReservationId = Convert.ToInt16(reader[0]);
roomReservationRequest.NoOfRooms = Convert.ToInt16(reader[1]);
roomReservationRequest.TypeOfRoom = reader[2].ToString();
roomReservationRequest.FromDate = Convert.ToDateTime(reader[3]);
roomReservationRequest.ToDate = Convert.ToDateTime(reader[4]);
roomReservationRequest.ContactPersonName = reader[5].ToString();
roomReservationRequest.ContactPersonMail = reader[6].ToString();
roomReservationRequest.ContactPersonMob = reader[7].ToString();
roomReservationRequest.Comments = reader[8].ToString();
roomReservationRequest.Status = reader[9].ToString();
reservedRooms.Add(roomReservationRequest);
}
}
finally
{
if (reader != null)
{
reader.Close();
reader.Dispose();
}

if (connection != null)
{
connection.Close();
connection.Dispose();
}
}
return reservedRooms.ToArray();
}
private SqlConnection GetConnection()
{

 

 

 

SqlConnection connection = new SqlConnection(connectionString);
try
{
connection.Open();
}
finally
{
}
return connection;
}
}
}

13. Declare two methods to the interface IService1 say ReserveRoom and GetReservations

namespace Practice.WCF
{
[ServiceContract]
public interface IService1
{
[OperationContract]
bool ReserveRoom(RoomReservationRequest reservationRequest);

[OperationContract]
RoomReservationRequest[] GetReservations(DateTime fromDate, DateTime toDate);
}
}

14. Implement the Interface ISErvice1 in Service1.svc.cs class. Create instance of class RoomReservationData which we implemented in Step-12 and use the same into the implemented methods.

namespace Practice.WCF
{
public class Service1 : IService1
{
#region IService1 Members
private RoomReservationData roomReservationData = new RoomReservationData();

public bool ReserveRoom(RoomReservationRequest reservationRequest)
{
return roomReservationData.ReserveRoom(reservationRequest);
}

 

 

public RoomReservationRequest[] GetReservations(DateTime fromDate, DateTime toDate)
{
return roomReservationData.GetReservations(fromDate, toDate);
}
#endregion
}
}

15. Now we are done with the implementation of WCF Service. Set the Service1 as Startup page. Run your WCF Application. Should get the following screen.
WCFRunning

16. Publish the WCF Service.

  1. To publish the service Right Click on Practice.WCF.csproj and select the Publish option
    PublishContextMenu
  2. Enter the location where you need to publish/ host the service.
    PublishDialog
  3. Click on Publish button to publish the site.

17. You may check the published WCF Service by typing the URL into browser
e.g. http://localhost/wcf/Service1.svc , a page same as Step-14 will appear.

7.0 How to Consume the WCF Service?

7.1 Generate the Class and Config File using svcutil.exe

You might have noticed the message displayed while browsing the service
ServiceMessage

Now, we need to generate the classes which our Client Application would use to consume the service.

We may generate the classes/configuration with the help of tool svcutil.exe. Follow the steps to generate the Class/Config file

  1. Open the command prompt and Go to the location where svcutil.exe is placed. You may find the same at following place “C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin”
  2. Write the following command and hit the “enter key” to generate the Class/Config files
    SVCUtil
  3. This would generate the Service1.cs and output.config files at the same location where svcutil.exe is placed i.e. “C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin”
  4. The class generated and the config file we need to include into our client application for consuming the service.

7.2 Create Client to Consume Service

1. Open Visual Studio

2. Go to Fileà New à Project

3. Select Windows Form Application

4. Create a Form similar to below
ClientApplication
5. Include the class generated by Step iii of Section 7.1

6. Right Click on project and select the option “Add Service Reference”
ServiceRefrence
7. Enter the URL/ Address where service is hosted and hit on “Go” button to find the service. You may see the Services Methods/Logic exposed by WCF Service
ServiceRefDialog

8. Click “OK” to add the service.
9. Double Click Room Reservation Enquiry button to write the logic. Make sure that you have imported the namespace of the generated class added to the project.

private void btnEnquiry_Click(object sender, EventArgs e)
{
Service1Client client = new Service1Client();
RoomReservationRequest[] reservationEnquiry = null;
reservationEnquiry = client.GetReservations(dateFromDate.Value, dateToDate.Value);

if (reservationEnquiry.Length > 0)
{
gvReservationData.DataSource = reservationEnquiry;
gvReservationData.Visible = true;
}
else
{
gvReservationData.Visible = false;
lblMessage.Text = "Sorry data not available.";
}
}

10. When we had added the reference of the Service to the client project one configuration file also would have been added to the application i.e. App.Config. Replace the node of this file by the node of the output.config file generated into “Step- iii” of “Section 7.1”

8.0 How to Use the Source?

Unzip the file WCF.zip, you may find the following files

1. DBBackup.zip

2. Source.zip

Restore/ Create Database

Unzip the file DBBackup.zip and restore the WCF.bak file to SQL Server Database or you may create the database as suggested in Step 6.1.

Now, Unzip the file Source.zip, you may find
1. WCFService
2. WCFClient
Publish/Host Client
i. Open the directory WCFService.
ii. Double click Practice.WCF.sln file to open the solution.
iii. Modify the web.config file of Service as suggested in Step-7 of Section-6.2.
iv. Publish the service as suggested in Step-16 of Section-6.2.
Use WCF Client to consume the services
i. Open WCFClient directory.
ii. Double click HelpDeskService.sln file to open the solution.
iii. Run the solution.
iv. Select the dates and hit on Enquiry button.
Note: You may need to modify App.Config file, if you have not published the WCF Service to local machine.

OOPS FAQ’s

Firs of all I would  like to inform and say sorry that you may find the questions in random order. In future if I could build the FAQ section big then definitely I would arrange the FAQ’s in proper seq.

Your feedback/ suggestion is most welcome to make the post more better. Thanks in advance….

In fact in FAQ section we will try to brush-up our OOPS knowledge with the help of some questions,
So, we will start now..

Question/ Scenario 1.0: 

Very frequently we use to write create the instance of a class like 

ClassA objClassA = new ClassA();

what does it mean by new ClassA();  or  what is the significance of new keyword?

Answer:

In order to answer this question I would like to take the example of an Web application,

Suppose we have a website which adds two numbers. Code for adding up the two numbers we have written in some class say Operation.cs or Operation.vb.

Now there are two person’s accessing the website say Person A and Person B. Both the persons may interested in adding the different different numbers for example (2,2) or (7,8) or any thing.

Writting new keword is nothing but intimiating the Framework/ Compiler that I want to create a new instance of the class or do not want to use the same instance which Person A is using to add (2,2). 
Question/ Scenario 2.0: 
We have tow C#/VB.NET classes say BaseClass and DerivedClass. BaseClass is a public class and contains four public methods,

  1. public double Add(double num1, double num2) {.......}
  2. public double Substract(double num1, double num2){.......}
  3. public double Multiply(double num1, double num2){.......}
  4. public double Divide(double num1, double num2){.......}

DerivedClass is also a public class and contains two public methods

  1. public double SimpleInterest(double price, double rate, double time){...............}
  2. public double CompoundInterest(double price, double rate, double time){...............}

Now DerivedClass derives BaseClass

public class DerivedClass : BaseClass { ...........}
Based on above scenario answer the following questions,

Question 2.1
Which of the following is a valid?  

       

  1. BaseClass baseClass = new DerivedClass();
  2. DerivedClass derClass = new BaseClass(); 
  3.  

Ans: 1, i.e. BaseClass baseClass = new DerivedClass();

but like this you would be able to access only public methods of BaseClass not the methods of derived class.

Question 2.2
Instance of the BaseClass is created like
BaseClass baseClass = new DerivedClass();
Which of the following is a valid?

  1. baseClass.SimpleInterest(1000,2,3);
  2. baseClass.Add(3,7);

Ans: 2, i.e. baseClass.Add(3,7);
because we had created object of BaseClass

Question 3.0: Does C# support multiple inheritance?
Answer: No. C# does not support multiple inheritance but multiple inheritance is possible with the help of Interfaces.

Question 4.0: What do you mean by an interface?
Read the illustration and answer the questions,
Answer: Interfaces describe a group of related functionalities that can belong to any class or struct. Interfaces can consist of methods, properties, events, indexers, or any combination of those four member types. An interface cannot contain fields. Interfaces members are automatically public.
When a class or struct is said to inherit an interface, it means that the class or struct provides an implementation for all of the members defined by the interface. The interface itself provides no functionality that a class or struct can inherit in the way that base class functionality can be inherited. However, if a base class implements an interface, the derived class inherits that implementation.

Classes and structs can inherit from interfaces in a manner similar to how classes can inherit a base class or struct, with two exceptions:

  1. A class or struct can inherit more than one interface.
  2. When a class or struct inherits an interface, it inherits only the method names and signatures, because the interface itself contains no implementations.

To implement an interface member, the corresponding member on the class must be public, non-static, and have the same name and signature as the interface member. Properties and indexers on a class can define extra accessors for a property or indexer defined on an interface. For example, an interface may declare a property with a get accessor, but the class implementing the interface can declare the same property with both a get and set accessor. However, if the property or indexer uses explicit implementation, the accessors must match.
Interfaces and interface members are abstract; interfaces do not provide a default implementation. For more information, see Abstract and Sealed Classes and Class Members.
Interfaces can inherit other interfaces. It is possible for a class to inherit an interface multiple times, through base classes or interfaces it inherits. In this case, the class can only implement the interface one time, if it is declared as part of the new class. If the inherited interface is not declared as part of the new class, its implementation is provided by the base class that declared it. It is possible for a base class to implement interface members using virtual members; in that case, the class inheriting the interface can change the interface behavior by overriding the virtual members.

Interfaces Quick Overview
An interface has the following properties:

  1. An interface is like an abstract base class: any non-abstract type inheriting the interface must implement all its members.
  2. An interface cannot be instantiated directly.
  3. Interfaces can contain events, indexers, methods and properties.
  4. Interfaces contain no implementation of methods.
  5. Classes and structs can inherit from more than one interface.
  6. An interface can itself inherit from multiple interfaces.

Question 4.1: Implement an interface say IOperations containing following method signatures

  1. Add : a method to add two double numbers
  2. Multiply : a method to multiply two double numbers


public interface IOperations
{
double Add(doubleb a, double b);
double Multiply(double a, double b);
}

गरीबी

 

आज देखा है एक गरीब का आशियाना , 

 आज ही जाना, 

 कितना मुश्किल है ईस दुनिया मे एक गरीब का जी पाना |

 अरे अन्दर की तो सुनिये साहब, भूल जाईये गा पलकें झपकाना |

 एक ही थी रोटी, जिसमें चार को था खाना |

 अब तक तो बूढी मां ने शुरु कर दिया था बच्चे को फ़ुसलना, 

 कहती है, बेटा – अब मेरा है क्या ठिकना,

 आज नहीं तो कल, मुझे तो है जाना ही जाना |

 पर तूं नहीं घबराना, दिया है जिसने चोंच, डाले गा वही दाना |

 दोस्तों यही है अपने देश के एक-एक गरीब का अफ़साना |

 ईस बार गरीबी ही रही ‘त्रिपाठी’ की कलम का निशाना |

 आईये हम सब मिल कर खातें हैं कसम,

 कि ईस देश से गरीबी को है मिटाना,

 क्योंकि,

 बड़ा ही मुश्किल है भारत माता के लिये ईस कलंक को सह पाना | 

 

                    - आषीश कुमार त्रिपाठी

                      गोरखपुर, 2001

Database Normalization

What does it mean by Normalization of a Database?

Definition: ”Normalization is the process of removing anomoly from a Database.”

Removing Anomoly in a database is mainly concern with,

  1. Eliminating redundant data (Storing the data in more than one table with proper relationships among the tables)
  2. Ensuring data dependencies make sense (data is should be stored into related table). 

Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.

Understanding Normalization in simple words.

You may consider the following example\scenario in order to understand the concept of normalization.

Suppose we have a normalized database (simple) with three tables 

  • TableA  (with 5 Columns)
  • TableB  (with 10 Columns)
  • TableC  (with 15 Columns)

An un normalized database for the above given database will contain only one table with 30 Columns (5 + 10 + 15) and off course no relationship between the data. But in such case data would be repeated very frequently i.e. data would be redundant.

The Normal Forms

Normal Forms are the guidelines provided by the Database community to achieve an optimal database model.

First Normal Form (1NF): First normal form (1NF) sets the very basic rules for an organized database:

  • Eliminate duplicative columns from the same table.
  • Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).

Second Normal Form (2NF): Second normal form (2NF) further addresses the concept of removing duplicative data:

  • Meet all the requirements of the first normal form.
  • Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
  • Create relationships between these new tables and their predecessors through the use of foreign keys.

Third Normal Form (3NF): Third normal form (3NF) goes one large step further:

  • Meet all the requirements of the second normal form.
  • Remove columns that are not dependent upon the primary key.

Fourth Normal Form (4NF): Finally, fourth normal form (4NF) has one additional requirement:

  • Meet all the requirements of the third normal form.
  • A relation is in 4NF if it has no multi-valued dependencies.

Note: These normalization guidelines are cumulative. For a database to be in 2NF, it must first fulfill all the criteria of a 1NF database. 

What is De-Normalization & its significance?
In order to understand the concept of De-Normalization we consider the example of Data Warehousing,
Data Warehousing is a concept which helps us to manage (store and retrieve) the data in an efficient manner. 
Going Back to De-Normalization….
Suppose you have Data Warehouse. You have come across a requirement to provide some set of data which needs to join 25 tables and all the tables contains huge data, huge means really very huge data. As we know that joins are little bit costly in terms of time, then you can imagine the scenario for joining 25 tables.
In this scenario rather than storing the data in a Normalized fashion, we can denormalize the database which will help us to achieve performance.

Older Posts »

Follow

Get every new post delivered to your Inbox.