Search This Blog

2009-12-23

Binding ASP .NET Treeview with LINQ to Stored Procedure

//--------------------------Table Structure---------------------------
USE [WMMM]
GO
/****** Object: Table [dbo].[MenuMaster] Script Date: 12/23/2009 16:41:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MenuMaster](
[ID] [bigint] NOT NULL,
[Name] [varchar](50) NULL,
[ParentID] [bigint] NULL,
CONSTRAINT [PK_MenuMaster] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

//-------------------------Stored Proc To Retive Data----------------------
USE [WMMM]
GO
/****** Object: StoredProcedure [dbo].[spMenuMasterSelect] Script Date: 12/23/2009 16:43:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spMenuMasterSelect]
AS
BEGIN
SET NOCOUNT ON;
SELECT ID,Name,ParentID from dbo.MenuMaster
END

GO
SET ANSI_PADDING OFF
//----------------------Code To Create Treeview---------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Web.UI.WebControls;
using DAL;

/// <summary>
/// Summary description for MenuBLL
/// </summary>
///

public class MenuBLL : IDisposable
{
WMMMDataContext db;
//list of all nodes
SortedList<int, MenuMaster> myMenus = new SortedList<int, MenuMaster>();
//list of all created nodes
SortedList<int, TreeNode> myCreatedNodes = new SortedList<int, TreeNode>();

public MenuBLL()
{
//
// TODO: Add constructor logic here
//
}
public void CreateMenu(MenuBO objMenuBo)
{
TreeView TreeView1 = objMenuBo.LeftTreeView;
TreeView1.Nodes.Clear();
db = new WMMMDataContext();
var found = from o in db.spMenuMasterSelect()
select new { o.ID, o.Name, o.ParentID };
MenuMaster mnuMaster = null;
foreach (var result in found)
{
mnuMaster = new MenuMaster();
mnuMaster.MenuID = Convert.ToInt32(result.ID);
mnuMaster.MenuName = result.Name;
mnuMaster.MenuParentId = Convert.ToInt32(result.ParentID);
myMenus.Add(mnuMaster.MenuID, mnuMaster);

}
TreeNode aNode = null;
foreach (int akey in myMenus.Keys)
{
string code = myMenus[akey].MenuID.ToString();
aNode = new TreeNode(myMenus[akey].MenuName, code);
CreateNode(aNode, TreeView1);
}
}
public void CreateNode(TreeNode aNode, TreeView TreeView1)
{
//This list stores all the nodes id from the current node to the ultimate parent
List<int> myPath = new List<int>();
if (!myCreatedNodes.ContainsValue(aNode))//if the node was not alreazdy created
{
int nodeId = 1001;
nodeId = Convert.ToInt32(aNode.Value);
//Building the current node path untill the ultimate parent
myPath.Add(nodeId);
while (nodeId != 0)
{
if (nodeId != 0)
{
nodeId = myMenus[nodeId].MenuParentId;
myPath.Add(nodeId);
}
}
}
//descending from Ultimate parent until the node
//if the current node does not exists we create it and add it to created nodes collection.
//if it has not a parent we add it to the treeview
//if it has a parent,the parent was already created because we come from it, so we add the current node to the parent.
TreeNode nodeToAdd = null, ParentNodeTofind = null;
for (int j = myPath.Count - 1; j > -1; j--)
{
if (myPath[j] != 0)
{
//checking for each path if the nodes was already created
if (!myCreatedNodes.Keys.Contains(myMenus[myPath[j]].MenuID))
{
//creating the node and adding it to the created nodes collection.
nodeToAdd = new TreeNode(myMenus[myPath[j]].MenuName, myMenus[myPath[j]].MenuID.ToString());
nodeToAdd.NavigateUrl = "../Nodes/Dashboard.aspx?NodeID=" + myMenus[myPath[j]].MenuID.ToString();
myCreatedNodes.Add(myMenus[myPath[j]].MenuID, nodeToAdd);
int parentId = myMenus[myPath[j]].MenuParentId;
//checking if the node has a parent
if (parentId == 0)//this node has no parent we add it to the tree view
{
TreeView1.Nodes.Add(nodeToAdd);
}

else//this node has a parent
{
//rerieving parent node (sure to find it)
ParentNodeTofind = myCreatedNodes[myMenus[myPath[j]].MenuParentId];
//we add the node to its parent childNodes
ParentNodeTofind.ChildNodes.Add(nodeToAdd);
}
}
}
}
}

#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

#endregion
private bool disposedValue = false;// To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!this.disposedValue)
{
if (disposing)
{
}
// TODO: free managed resources when explicitly called
//if (dbCommand != null)
//{
// dbCommand.Dispose();
// //GC.SuppressFinalize(dbCommand);
//}

}
// TODO: free shared unmanaged resources
this.disposedValue = true;
}
}
public class MenuMaster
{

private string _MenuName;
private int _MenuID;
private int _MenuParentId;


public string MenuName
{
get { return _MenuName; }

set { _MenuName = value; }
}
public int MenuID
{
get { return _MenuID; }
set { _MenuID = value; }
}
public int MenuParentId
{
get { return _MenuParentId; }
set { _MenuParentId = value; }
}
}


//--------------------------Tree View in ASPX Page---------------
<asp:TreeView ID="tvLeftMenu" runat="server" CssClass="input-value" ShowLines="True"
BackColor="Transparent" BorderColor="DarkGray" Font-Bold="True" Font-Size="Small"
ForeColor="Black" ExpandDepth="13" ShowExpandCollapse="false" Width="100px" Font-Names="Times New Roman">
</asp:TreeView>

//-----------------------SQL Table Data-----------------

//------------------------Output Of the Treeview-------------------

//------------------------For LINQ To Stored Proc Visit the following URL
Introduction to Linq To Stored Procedure

2009-12-20

Create Multi Layer Architecture using WCF

WCF is the Microsoft next generation technology for developing distributed applications.WCF is based on SOA.So,if we want to expose our component as a service,we can use WCF to host the service in IIS,WAS,Self Hosting or managed windows service.
In the following example ,the main component is written in CalculateNumber class which contains a method Calculate.The calculate method takes two integer number and return an integer.So this is the component class.
Now we have created CalculateServiceLayer class in the another project to make the component class(CalculateNumber ) to be available in the WCF Host.So in one side ,it will contain System.ServiceModel namespace for WCF and on the other side it will refer the component class CalculateNumber.
Then as we need to host the service we need a console application projectHost) to hosting the service.The Host application configure the necessary settings like address,binding and contract and start the service in a particular address mentioned in the end point.
Now the service is available for invoking.So we will create a client application (web/windows) to invoke the service.
Lets start the step by step development.

Step 1.Create a Class Library Project "CalculateNumber"


Step 2. Write a method in the class and build your component class CalculateNumber.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CalculateNumber
{
public class CalculateNumber
{
public int Calculate(int x, int y)
{
return x + y;
}
}
}


Step 3.Add a new project (Service Layer) in the solution


Step 4.Choose a class library project and put the project name "CalculateServiceLayer".


Step 5.Add a reference of System.ServiceModel and your component class dll i.e CalculateNumber.dll


Step 6.Modify the class name Class1.cs to ICalculateSevice.cs and copy the entire code in place of existing code in Class1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CalculateNumber;
using System.ServiceModel;

namespace CalculateServiceLayer
{
[ServiceContract]
interface ICalculateSevice
{
[OperationContract]
int CalcalculateNumber(int m,int n);
}
}

Step 7.Add an another class file CalculateServiceType.cs and write the following code.Then build your application


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CalculateNumber;
using System.ServiceModel;

namespace CalculateServiceLayer
{
public class CalculateServiceType:ICalculateSevice
{
CalculateNumber.CalculateNumber cn;
#region ICalculateSevice Members

public int CalcalculateNumber(int m, int n)
{
cn=new CalculateNumber.CalculateNumber();
return cn.Calculate(m, n);
}

#endregion
}
}

Step 8.Now add a Host console application in the same solution


Step 9.Add a reference of System.ServiceModel and CalculateServiceLayer.dll.
Open the Program.cs and write the code as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using CalculateServiceLayer;

namespace Host
{
class Program
{
static void Main(string[] args)
{
ServiceHost sh = new ServiceHost(typeof(CalculateServiceLayer.CalculateServiceType));
sh.Open();
Console.WriteLine("The Service is ready to use");
Console.ReadKey(true);
sh.Close();

}
}
}

Step 10.Add an App.config file in your Host project


Step 11.Write the necessary configuration in your App.config file as follows
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="NewBehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="NewBehavior" name="CalculateServiceLayer.CalculateServiceType">
<endpoint address="basic" binding="basicHttpBinding" bindingConfiguration=""
contract="CalculateServiceLayer.ICalculateSevice" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:3333/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>

Step 12.Now your overall solution structure will be as follows


Step 13.Right click on your Host application and click on "Start new instance" under Debug menu


Step 14.You can see the following console output


Step 15.Now create a web application that will invoke the Wcf service.Right click on the Reference and click on "Add service reference".


Step 16.Put the address "http://localhost:3333/" ,click on Go and then select the service and click OK.Before that make sure your host application is running.


Step 17.Now implement the service in your aspx page as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ImplementCalculateNumber
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ServiceReference1.CalculateSeviceClient myproxy = new ImplementCalculateNumber.ServiceReference1.CalculateSeviceClient();
Response.Write(myproxy.CalcalculateNumber(19, 30).ToString());
}
}
}

Step 18.Run your application ,you can see the following output


Step 19.If you modify in the component or service layer,update the service reference in the client (web) application

2009-12-19

Introduction to Linq To Stored Procedure

LINQ to SQL provides a runtime infrastructure for managing relational data as objects without losing the ability to query. Your application is free to manipulate the objects while LINQ to SQL stays in the background tracking your changes automatically.It is possible to migrate current ADO.NET solutions to LINQ to SQL in a piecemeal fashion (sharing the same connections and transactions) since LINQ to SQL is simply another component in the ADO.NET family. LINQ to SQL also has extensive support for stored procedures, allowing reuse of the existing enterprise assets. In addition it can filter data in .NET end which are coming from the stored proc.
Following are the steps describe you how LINQ to Stored proc works together.
Step 1-First create a table in your SQL server database-

I have created a table MyTable in the Northwind database.The table contains three feilds(MyID int,MyName Varchar,MyAddress varchar) MyID is a autogenerate number and primary key in this table.
Put some data in yout table

Step 2.Write the following stored proc in your database
-----------------------------------------------------------------------------------------------------------------------
USE [Northwind]
GO
/****** Object: StoredProcedure [dbo].[spMyTableDelete] Script Date: 12/07/2009 00:08:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spMyTableDelete]

(
@MyID int
-- @MyName varchar(50),
-- @MyAddress varchar(50)
)

AS
BEGIN
SET NOCOUNT ON;
DELETE from dbo.MyTable where MyID=@MyID
--SELECT MyID,MyName,MyAddress from dbo.MyTable
END
--select * from MyTable

-------------------------------------------------------------------------------------------------------------------------
USE [Northwind]
GO
/****** Object: StoredProcedure [dbo].[spMyTableInsert] Script Date: 12/07/2009 00:09:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spMyTableInsert]

(
@MyName varchar(50),
@MyAddress varchar(50)
)

AS
BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.MyTable(MyName,MyAddress)VALUES(@MyName,@MyAddress)
END
------------------------------------------------------------------------------------------------------------------------
USE [Northwind]
GO
/****** Object: StoredProcedure [dbo].[spMyTableSelect] Script Date: 12/07/2009 00:10:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spMyTableSelect]

-- (
-- @MyID int,
-- @MyName varchar(50),
-- @MyAddress varchar(50)
-- )

AS
BEGIN
SET NOCOUNT ON;
SELECT MyID,MyName,MyAddress from dbo.MyTable
END
--select * from MyTable
----------------------------------------------------------------------------------------------------------------------------
USE [Northwind]
GO
/****** Object: StoredProcedure [dbo].[spMyTableSelectMulti] Script Date: 12/07/2009 00:10:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spMyTableSelectMulti]

-- (
-- @MyID int
-- @MyName varchar(50),
-- @MyAddress varchar(50)
-- )

AS

BEGIN
SET NOCOUNT ON;

SELECT MyID,MyName,MyAddress from dbo.MyTable where MyID=2
SELECT MyID,MyName,MyAddress from dbo.MyTable where MyID=1
END
--select * from MyTable
----------------------------------------------------------------------------------------------------------------------
USE [Northwind]
GO
/****** Object: StoredProcedure [dbo].[spMyTableSelectMultiWithOutputParam] Script Date: 12/07/2009 00:11:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spMyTableSelectMultiWithOutputParam]

(
@MyID int,
@MyName varchar(50) output
-- @MyAddress varchar(50)
)

AS

BEGIN
SET NOCOUNT ON;

SELECT MyID,MyName,MyAddress from dbo.MyTable
SELECT @MyName=(SELECT MyName from dbo.MyTable where MyID=@MyID)
END
--select * from MyTable
------------------------------------------------------------------------------------------------------------------------------

USE [Northwind]
GO
/****** Object: StoredProcedure [dbo].[spMyTableUpdate] Script Date: 12/07/2009 00:12:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spMyTableUpdate]

(
@MyID int,
@MyName varchar(50),
@MyAddress varchar(50)
)

AS
BEGIN
SET NOCOUNT ON;
UPDATE dbo.MyTable SET MyName=@MyName,MyAddress=@MyAddress
WHERE MyID=@MyID
END

Step 3.Create a new web site in .NET IDE


Step 4.Choose "Add New Item" on your App_Code folder


Step 5.Choose "LINQ to SQL Classes" in yourAdd New Item Dialog and put the file name "MyDataClasses.dbml".


Step 6.Open the MyDataClasses.dbml and modify the name "MyDataContext".Click on "Server Explorer" in MyDataClasses.dbml


Step7.In the Server Explorer click on "Connect to database" icon


Step 8.In "Add Connection" dialog put the server name,database name and required credentials

Step 9.Drag the requird Stored proc in your Method Pane

Step 10.If the Method Pane is not visible,right click on the designer and click on "Show Methods Pane".

Step 11.Now go to your Default.aspx page and create few buttons ,event and a gridview
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grdData" runat="server">
</asp:GridView>
</div>
<asp:Button ID="btnInsert" runat="server" OnClick="btnInsert_Click" Text="Insert" />
<asp:Button ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" Text="Update" />
<asp:Button ID="btnSelect" runat="server" OnClick="btnSelect_Click" Text="Select" />
<asp:Button ID="btnDelete" runat="server" OnClick="btnDelete_Click" Text="Delete" />
<asp:Button ID="btnSelectMulti" runat="server" OnClick="btnSelectMulti_Click" Text="SelectMultipleDatatable" />
<asp:Button ID="btnSelectMultiWithOutputParam" runat="server" OnClick="btnSelectMultiWithOutputParam_Click"
Text="SelectMultipleWithOutputParameter" />
</form>
</body>
</html>

Step 12.In the Default.aspx.cs call the required stored procedure for Insert ,update ,select and Delete
MyDataContext db = new MyDataContext();

protected void btnInsert_Click(object sender, EventArgs e)
{
var q3 = db.spMyTableInsert("Indra", "Jadavpur");
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
var update = db.spMyTableUpdate(2,"Indra", "Jadavpur");

}
protected void btnSelect_Click(object sender, EventArgs e)
{

var Select2 = from o in db.spMyTableSelect()
where o.MyID <= 12 select new { o.MyID, o.MyName, o.MyAddress };
grdData.DataSource = Select2;
grdData.DataBind();
} protected void btnDelete_Click(object sender, EventArgs e)
{
var delete = db.spMyTableDelete(3);
}
Step 13.Now if you like to call a stored proc like dbo.spMyTableSelectMultiWithOutputParam which has a output param write teh follwoing code in your btnSelectMultiWithOutputParam click event
protected void btnSelectMultiWithOutputParam_Click(object sender, EventArgs e)
{
string strCustName = "";
var q2 = db.spMyTableSelectMultiWithOutputParam(1, ref strCustName);
Response.Write(strCustName.ToString());
grdData.DataSource = q2; grdData.DataBind();
}
The spMyTableSelectMultiWithOutputParam is like this
ALTER PROCEDURE dbo.spMyTableSelectMultiWithOutputParam
(
@MyID int, @MyName varchar(50) output
) AS
BEGIN
SET NOCOUNT ON;
SELECT MyID,MyName,MyAddress from dbo.MyTable
SELECT @MyName=(SELECT MyName from dbo.MyTable where MyID=@MyID)
END Step
14.Now if you want to call a storedproc which is returning multiple select statement like spMyTableSelectMulti,do the following steps---
The stored proc is like this
ALTER PROCEDURE dbo.spMyTableSelectMulti
AS
BEGIN
SET NOCOUNT ON;
SELECT MyID,MyName,MyAddress from dbo.MyTable where MyID=2
SELECT MyID,MyName,MyAddress from dbo.MyTable where MyID=1
END
Open the MyDataClassesDesigner.cs and comment the class spMyTableSelectMultiResult .

Then create a new class file clsMultiRecords.cs in App_code and create two partial class spMyTableSelectMultiResult and spMyTableSelectMultiResult2 First Class return the first SQL query and the second one return the second sql query.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

/// <summary>
/// Summary description for clsMultiRecords
/// </summary>
public class clsMultiRecords
{
public clsMultiRecords()
{
//
// TODO: Add constructor logic here
//
}
//[Function(Name = "dbo.spMyTableSelectMulti"), ResultType(typeof(clsMultiRecords.spMyTableSelectMultiResult)), ResultType(typeof(clsMultiRecords.spMyTableSelectMultiResult2))]
//public IMultipleResults spMyTableSelectMulti()
//{
// IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
// return ((IMultipleResults)(result.ReturnValue));
//}

public partial class spMyTableSelectMultiResult
{

private int _MyID;

private string _MyName;

private string _MyAddress;

public spMyTableSelectMultiResult()
{
}

[Column(Storage = "_MyID", DbType = "Int NOT NULL")]
public int MyID
{
get
{
return this._MyID;
}
set
{
if ((this._MyID != value))
{
this._MyID = value;
}
}
}

[Column(Storage = "_MyName", DbType = "VarChar(50)")]
public string MyName
{
get
{
return this._MyName;
}
set
{
if ((this._MyName != value))
{
this._MyName = value;
}
}
}

[Column(Storage = "_MyAddress", DbType = "VarChar(50)")]
public string MyAddress
{
get
{
return this._MyAddress;
}
set
{
if ((this._MyAddress != value))
{
this._MyAddress = value;
}
}
}
}
public partial class spMyTableSelectMultiResult2
{

private int _MyID;

private string _MyName;

private string _MyAddress;

public spMyTableSelectMultiResult2()
{
}

[Column(Storage = "_MyID", DbType = "Int NOT NULL")]
public int MyID
{
get
{
return this._MyID;
}
set
{
if ((this._MyID != value))
{
this._MyID = value;
}
}
}

[Column(Storage = "_MyName", DbType = "VarChar(50)")]
public string MyName
{
get
{
return this._MyName;
}
set
{
if ((this._MyName != value))
{
this._MyName = value;
}
}
}

[Column(Storage = "_MyAddress", DbType = "VarChar(50)")]
public string MyAddress
{
get
{
return this._MyAddress;
}
set
{
if ((this._MyAddress != value))
{
this._MyAddress = value;
}
}
}
}
}



Again open the DataClassesDesigner.cs and delete the follwoing portion

[Function(Name = "dbo.spMyTableSelectMulti")]
public ISingleResult spMyTableSelectMulti()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return ((ISingleResult)(result.ReturnValue));
}

and write the following code in place of that

[Function(Name = "dbo.spMyTableSelectMulti"), ResultType(typeof(clsMultiRecords.spMyTableSelectMultiResult)), ResultType(typeof(clsMultiRecords.spMyTableSelectMultiResult2))]
public IMultipleResults spMyTableSelectMulti()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return ((IMultipleResults)(result.ReturnValue));
}

This method will return the IMultipleResults instead of ISingleResult. Mind it,if you open the dbml(MyDataClasses.dbml not MyDataClasses.designer.cs) file and save/modify it, this above portion will be overridden by ISingleResult. Now go to the click event of btnSelectMulti and write the following code
protected void btnSelectMulti_Click(object sender, EventArgs e)
{
IMultipleResults results = new MyDataContext().spMyTableSelectMulti(); List result1 = results.GetResult().ToList();

List result2 = results.GetResult().ToList();


grdData.DataSource = result2;
grdData.DataBind();
}

Step 15.Now run your application ,you can now see the following output,click on different button to obeserve the operation



I am attaching the complete code for Default.aspx.cs ,MyDataContext class and clsMultiRecords.cs

Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data.Linq;

public partial class _Default : System.Web.UI.Page
{
MyDataContext db = new MyDataContext();
protected void Page_Load(object sender, EventArgs e)
{




}
protected void btnInsert_Click(object sender, EventArgs e)
{
var q3 = db.spMyTableInsert("Indra", "Jadavpur");
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
var update = db.spMyTableUpdate(2,"Indra", "Jadavpur");

}
protected void btnSelect_Click(object sender, EventArgs e)
{


var Select2 = from o in db.spMyTableSelect()
where o.MyID <= 12
select new { o.MyID, o.MyName, o.MyAddress };

grdData.DataSource = Select2;
grdData.DataBind();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
var delete = db.spMyTableDelete(3);
}
protected void btnSelectMulti_Click(object sender, EventArgs e)
{
IMultipleResults results = new MyDataContext().spMyTableSelectMulti();
List<clsMultiRecords.spMyTableSelectMultiResult> result1 = results.GetResult<clsMultiRecords.spMyTableSelectMultiResult>().ToList();

List<clsMultiRecords.spMyTableSelectMultiResult2> result2 = results.GetResult<clsMultiRecords.spMyTableSelectMultiResult2>().ToList();



grdData.DataSource = result2;
grdData.DataBind();
}
protected void btnSelectMultiWithOutputParam_Click(object sender, EventArgs e)
{
string strCustName = "";
var q2 = db.spMyTableSelectMultiWithOutputParam(1, ref strCustName);
Response.Write(strCustName.ToString());
grdData.DataSource = q2;
grdData.DataBind();
}
}

MyDataContext class
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3053
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;



[System.Data.Linq.Mapping.DatabaseAttribute(Name="Northwind")]
public partial class MyDataContext : System.Data.Linq.DataContext
{

private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();

#region Extensibility Method Definitions
partial void OnCreated();
#endregion

public MyDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}

public MyDataContext(string connection) :
base(connection, mappingSource)
{
OnCreated();
}

public MyDataContext(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}

public MyDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}

public MyDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}

[Function(Name="dbo.spMyTableInsert")]
public int spMyTableInsert([Parameter(Name="MyName", DbType="VarChar(50)")] string myName, [Parameter(Name="MyAddress", DbType="VarChar(50)")] string myAddress)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), myName, myAddress);
return ((int)(result.ReturnValue));
}

[Function(Name="dbo.spMyTableUpdate")]
public int spMyTableUpdate([Parameter(Name="MyID", DbType="Int")] System.Nullable<int> myID, [Parameter(Name="MyName", DbType="VarChar(50)")] string myName, [Parameter(Name="MyAddress", DbType="VarChar(50)")] string myAddress)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), myID, myName, myAddress);
return ((int)(result.ReturnValue));
}

[Function(Name="dbo.spMyTableSelect")]
public ISingleResult<spMyTableSelectResult> spMyTableSelect()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return ((ISingleResult<spMyTableSelectResult>)(result.ReturnValue));
}

[Function(Name="dbo.spMyTableDelete")]
public int spMyTableDelete([Parameter(Name="MyID", DbType="Int")] System.Nullable<int> myID)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), myID);
return ((int)(result.ReturnValue));
}

//[Function(Name = "dbo.spMyTableSelectMulti")]
//public ISingleResult<spMyTableSelectMultiResult> spMyTableSelectMulti()
//{
// IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
// return ((ISingleResult<spMyTableSelectMultiResult>)(result.ReturnValue));
//}
[Function(Name = "dbo.spMyTableSelectMulti"), ResultType(typeof(clsMultiRecords.spMyTableSelectMultiResult)), ResultType(typeof(clsMultiRecords.spMyTableSelectMultiResult2))]
public IMultipleResults spMyTableSelectMulti()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return ((IMultipleResults)(result.ReturnValue));
}
//[Function(Name = "dbo.spMyTableSelectMulti")]
//public IMultipleResults spMyTableSelectMulti()
//{
// IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
// return (IMultipleResults)(result.ReturnValue);
//}

[Function(Name="dbo.spMyTableSelectMultiWithOutputParam")]
public ISingleResult<spMyTableSelectMultiWithOutputParamResult> spMyTableSelectMultiWithOutputParam([Parameter(Name="MyID", DbType="Int")] System.Nullable<int> myID, [Parameter(Name="MyName", DbType="VarChar(50)")] ref string myName)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), myID, myName);
myName = ((string)(result.GetParameterValue(1)));
return ((ISingleResult<spMyTableSelectMultiWithOutputParamResult>)(result.ReturnValue));
}
}

public partial class spMyTableSelectResult
{

private int _MyID;

private string _MyName;

private string _MyAddress;

public spMyTableSelectResult()
{
}

[Column(Storage="_MyID", DbType="Int NOT NULL")]
public int MyID
{
get
{
return this._MyID;
}
set
{
if ((this._MyID != value))
{
this._MyID = value;
}
}
}

[Column(Storage="_MyName", DbType="VarChar(50)")]
public string MyName
{
get
{
return this._MyName;
}
set
{
if ((this._MyName != value))
{
this._MyName = value;
}
}
}

[Column(Storage="_MyAddress", DbType="VarChar(50)")]
public string MyAddress
{
get
{
return this._MyAddress;
}
set
{
if ((this._MyAddress != value))
{
this._MyAddress = value;
}
}
}
}

//public partial class spMyTableSelectMultiResult
//{

// private int _MyID;

// private string _MyName;

// private string _MyAddress;

// public spMyTableSelectMultiResult()
// {
// }

// [Column(Storage="_MyID", DbType="Int NOT NULL")]
// public int MyID
// {
// get
// {
// return this._MyID;
// }
// set
// {
// if ((this._MyID != value))
// {
// this._MyID = value;
// }
// }
// }

// [Column(Storage="_MyName", DbType="VarChar(50)")]
// public string MyName
// {
// get
// {
// return this._MyName;
// }
// set
// {
// if ((this._MyName != value))
// {
// this._MyName = value;
// }
// }
// }

// [Column(Storage="_MyAddress", DbType="VarChar(50)")]
// public string MyAddress
// {
// get
// {
// return this._MyAddress;
// }
// set
// {
// if ((this._MyAddress != value))
// {
// this._MyAddress = value;
// }
// }
// }
//}

public partial class spMyTableSelectMultiWithOutputParamResult
{

private int _MyID;

private string _MyName;

private string _MyAddress;

public spMyTableSelectMultiWithOutputParamResult()
{
}

[Column(Storage="_MyID", DbType="Int NOT NULL")]
public int MyID
{
get
{
return this._MyID;
}
set
{
if ((this._MyID != value))
{
this._MyID = value;
}
}
}

[Column(Storage="_MyName", DbType="VarChar(50)")]
public string MyName
{
get
{
return this._MyName;
}
set
{
if ((this._MyName != value))
{
this._MyName = value;
}
}
}

[Column(Storage="_MyAddress", DbType="VarChar(50)")]
public string MyAddress
{
get
{
return this._MyAddress;
}
set
{
if ((this._MyAddress != value))
{
this._MyAddress = value;
}
}
}
}
#pragma warning restore 1591

clsMultiRecords.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

/// <summary>
/// Summary description for clsMultiRecords
/// </summary>
public class clsMultiRecords
{
public clsMultiRecords()
{
//
// TODO: Add constructor logic here
//
}
//[Function(Name = "dbo.spMyTableSelectMulti"), ResultType(typeof(clsMultiRecords.spMyTableSelectMultiResult)), ResultType(typeof(clsMultiRecords.spMyTableSelectMultiResult2))]
//public IMultipleResults spMyTableSelectMulti()
//{
// IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
// return ((IMultipleResults)(result.ReturnValue));
//}

public partial class spMyTableSelectMultiResult
{

private int _MyID;

private string _MyName;

private string _MyAddress;

public spMyTableSelectMultiResult()
{
}

[Column(Storage = "_MyID", DbType = "Int NOT NULL")]
public int MyID
{
get
{
return this._MyID;
}
set
{
if ((this._MyID != value))
{
this._MyID = value;
}
}
}

[Column(Storage = "_MyName", DbType = "VarChar(50)")]
public string MyName
{
get
{
return this._MyName;
}
set
{
if ((this._MyName != value))
{
this._MyName = value;
}
}
}

[Column(Storage = "_MyAddress", DbType = "VarChar(50)")]
public string MyAddress
{
get
{
return this._MyAddress;
}
set
{
if ((this._MyAddress != value))
{
this._MyAddress = value;
}
}
}
}
public partial class spMyTableSelectMultiResult2
{

private int _MyID;

private string _MyName;

private string _MyAddress;

public spMyTableSelectMultiResult2()
{
}

[Column(Storage = "_MyID", DbType = "Int NOT NULL")]
public int MyID
{
get
{
return this._MyID;
}
set
{
if ((this._MyID != value))
{
this._MyID = value;
}
}
}

[Column(Storage = "_MyName", DbType = "VarChar(50)")]
public string MyName
{
get
{
return this._MyName;
}
set
{
if ((this._MyName != value))
{
this._MyName = value;
}
}
}

[Column(Storage = "_MyAddress", DbType = "VarChar(50)")]
public string MyAddress
{
get
{
return this._MyAddress;
}
set
{
if ((this._MyAddress != value))
{
this._MyAddress = value;
}
}
}
}
}

2009-12-14

Estimation using Fuction Point Analysis-Phase Considaration and cost calculation(Part 6)

We generally distribute the phase of a project in the following manner after getting the total Man Days

And the we can asign resources in the following manner ,it can vary according to your company strength or company policy.this is just a sample

Now you can calculate your total cost for your project depending on the salary of your team member and other cost.

Estimation using Fuction Point Analysis-Productivity Factor(Part 5)

To convert the adjusted FP to man hour or man hour we need to calculate the Productivity factor that indicates how many FP your company can achive in a day.

Estimation using Fuction Point Analysis-GSC(Part 4)


Now that we have covered five Fundamental of FPA-EI,EO,EQ,EIF,ILF.
Lets move ahead General System Characteristics(GSC) and adjusted function point.On the top of those five things we will apply GSC.
I am providing a GSC template where you have to put the value first in place of "1" in this case and calculate GSC.















GSC factorDefinitionsValue
Data CommunicationsHow many communication facilities are there to aid in the transfer or exchange of information with the application or system?
Data Communications describes the degree to which the application communicates directly with the processor.
Score As Descriptions To Determine Degree of Influence:
0. Application is pure batch processing or a stand-alone PC.
1. Application is batch but has remote data entry or remote printing.
2. Application is batch but has remote data entry and remote printing.
3. Application includes online data collection or TP (teleprocessing) front
end to a batch process or query system.
4. Application is more than a front-end, but supports only one type of TP
communications protocol.
5. Application is more than a front-end, and supports more than one type
of TP communications protocol.
1
Distributed Data Processing


How are distributed data and processing functions handled?
Distributed Data Processing describes the degree to which the application
transfers data among components of the application.
Score As Descriptions To Determine Degree of Influence
0. Application does not aid the transfer of data or processing functions
between components of the system.
1. Application prepares data for user processing on another component of
the system such as PC spreadsheets and PC DBMS.
2. Data is prepared for transfer, then is transferred and processed on
another component of the system (not for end-user processing).
3. Distributed processing and data transfer are online and in one direction only.
4. Distributed processing and data transfer are online and in both
directions.
5. Processing functions are dynamically performed on the most appropriate
component of the system.
1
Performance

Did the user require response time or throughput?
Performance describes the degree to which response time and throughput
performance considerations influenced the application development.

Score As Descriptions To Determine Degree of Influence:
0. No special performance requirements were stated by the user.
1. Performance and design requirements were stated and reviewed but no special actions
were required.
2. Response time or throughput is critical during peak hours. No special design for
CPU utilization was required. Processing deadline is for the next business day.
3. Response time or throughput is critical during all business hours. No special design for
CPU utilization was required. Processing deadline requirements with interfacing systems
are constraining.
4. In addition, stated user performance requirements are stringent enough to
require performance analysis tasks in the design phase.
5. In addition, performance analysis tools were used in the design, development,
and/or implementation phases to meet the stated user performance requirements.
1
Heavily Used Configuration

How heavily used is the current hardware platform where the application will be executed?
Heavily Used Configuration describes the degree to which computer resource
restrictions influenced the development of the application.

Score As Descriptions To Determine Degree of Influence:
0. No explicit or implicit operational restrictions are included.
1. Operational restrictions do exist, but are less restrictive than a typical application.
No special effort is needed to meet the restrictions.
2. Some security or timing considerations are included.
3. Specific processor requirements for a specific piece of the application are included.
4. Stated operation restrictions require special constraints on the application in the
central processor or a dedicated processor.
5. In addition, there are special constraints on the application in the
distributed components of the system.
1
Transaction Rate

How frequently are transactions executed; daily, weekly, monthly, etc.?
Transaction Rate describes the degree to which the rate of business
transactions influenced the development of the application.

Score As Descriptions To Determine Degree of Influence:
0. No peak transaction period is anticipated.
1. Peak transaction period (e.g., monthly, quarterly, seasonally, annually) is anticipated.
2. Weekly peak transaction period is anticipated.
3. Daily peak transaction period is anticipated.
4. High transaction rate(s) stated by the user in the application requirements or service
level agreements are high enough to require performance analysis tasks in the
design phase.
5. High transaction rate(s) stated by the user in the application requirements or service
level agreements are high enough to require performance analysis tasks and, in
addition, require the use of performance analysis tools in the design, development,
and/or installation phases.
1
On-line Data Entry

What percentage of the information is entered On-Line?
Online Update describes the degree to which internal logical files are updated
online.

Online Data Entry describes the degree to which data is entered through
interactive transactions.

Score As Descriptions To Determine Degree of Influence:
0. All transactions are processed in batch mode.
1. 1% to 7% of transactions are interactive data entry.
2. 8% to 15% of transactions are interactive data entry.
3. 16% to 23% of transactions are interactive data entry.
4. 24% to 30% of transactions are interactive data entry.
5. More than 30% of transactions are interactive data entry.
1
End-user Efficiency

Was the application designed for end-user efficiency?
End-User Efficiency describes the degree of consideration for human factors
and ease of use for the user of the application measured.

The online functions provided emphasize a design for end-user efficiency. The
design includes:
· Navigational aids (for example, function keys, jumps, dynamically generated menus)
· Menus
· Online help and documents
· Automated cursor movement
· Scrolling
· Remote printing via online transactions
· Pre-assigned function keys
· Batch jobs submitted from online transactions
· Cursor selection of screen data
· Heavy use of reverse video, highlighting, colors underlining, and other indicators
· Hard copy user documentation of online transactions
· Mouse interface
· Pop-up windows
· As few screens as possible to accomplish a business function
· Bilingual support (supports two languages; count as four items)
· Multilingual support (supports more than two languages; count as six items)

Score As Descriptions To Determine Degree of Influence
0. None of the above.
1. One to three of the above.
2. Four to five of the above.
3. Six or more of the above, but there are no specific user requirements related to efficiency.
4. Six or more of the above, and stated requirements for end-user efficiency are strong
enough to require design tasks for human factors to be included (for example, minimize
key strokes, maximize defaults, use of templates).
5. Six or more of the above, and stated requirements for end-user efficiency are strong
enough to require use of special tools and processes to demonstrate that the objectives
have been achieved.
1
On-line Updates

How many ILF’s are updated by On-Line transaction?
Online Update describes the degree to which internal logical files are updated
online.

Score As Descriptions To Determine Degree of Influence:
0. None.
1. Online update of one to three control files is included. Volume of updating is low
and recovery is easy.
2. Online update of four or more control files is included. Volume of updating is low
and recovery easy.
3. Online update of major internal logical files is included.
4. In addition, protection against data lost is essential and has been specially designed
and programmed in the system.
5. In addition, high volumes bring cost considerations into the recovery process.
Highly automated recovery procedures with minimum operator intervention are included.
1
Complex ProcessingDoes the application have extensive logical or mathematical processing?
Complex processing describes the degree to which processing logic influenced
the development of the application.

The following components are present:
· Sensitive control (for example, special audit processing) and/or application
specific security processing
· Extensive logical processing
· Extensive mathematical processing
· Much exception processing resulting in incomplete transactions that must be
processed again (for example, incomplete ATM transactions caused by TP
interruption, missing data values, or failed validations)
· Complex processing to handle multiple input/output possibilities (for example,
multimedia, or device independence)

Score As Descriptions To Determine Degree of Influence:
0. None of the above.
1. Any one of the above.
2. Any two of the above.
3. Any three of the above.
4. Any four of the above.
5. All five of the above.
1
Reusability

Was the application developed to meet one or many user’s needs?
Reusability describes the degree to which the application and the code in the application
have been specifically designed, developed, and supported to be usable in other applications.

Score As Descriptions To Determine Degree of Influence:
0. No reusable code.
1. Reusable code is used within the application.
2. Less than 10% of the application considered more than one user's needs.
3. Ten percent (10%) or more of the application considered more than one user's needs.
4. The application was specifically packaged and/or documented to ease re-use, and
the application is customized by the user at source code level.
5. The application was specifically packaged and/or documented to ease re-use, and
the application is customized for use by means of user parameter maintenance.
1
Installation Ease

How difficult is conversion and installation?
Installation Ease describes the degree to which conversion from previous environments influenced the development of the application.

Score As Descriptions To Determine Degree of Influence:
0. No special considerations were stated by the user, and no special setup is required
for installation.
1. No special considerations were stated by the user but special setup is required for
installation.
2. Conversion and installation requirements were stated by the user, and conversion
and installation guides were provided and tested. The impact of conversion on the project
is not considered to be important.
3. Conversion and installation requirements were stated by the user, and conversion
and installation guides were provided and tested. The impact of conversion on the project
is considered to be important.
4. In addition to 2 above, automated conversion and installation tools were provided and
tested.
5. In addition to 3 above, automated conversion and installation tools were provided and
tested.
1
Operational Ease

How effective and/or automated are start-up, back up, and recovery procedures?
Operational Ease describes the degree to which the application attends to
operational aspects, such as start-up, back-up, and recovery processes.

Score As Descriptions To Determine Degree of Influence:
0. No special operational considerations other than the normal back-up procedures
were stated by the user.
1 - 4 One, some, or all of the following items apply to the application. Select
all that apply. Each item has a point value of one, except as noted otherwise.
· Effective start-up, back-up, and recovery processes were provided,
but operator intervention is required.
· Effective start-up, back-up, and recovery processes were provided,
but no operator intervention is required (count as two items).
· The application minimizes the need for tape mounts.
· The application minimizes the need for paper handling.
5. The application is designed for unattended operation. Unattended operation means
no operator intervention is required to operate the system other than to start up or
shut down the application. Automatic error recovery is a feature of the application.
1
Multiple Sites

Was the application specifically designed, developed, and supported to be installed at multiple sites for multiple organizations?
Multiple Sites describes the degree to which the application has been
developed for multiple locations and user organizations.

Score As Descriptions To Determine Degree of Influence:
0. User requirements do not require considering the needs of more than one user/installation site.
1. Needs of multiple sites were considered in the design, and the application is designed to
operate only under identical hardware and software environments.
2. Needs of multiple sites were considered in the design, and the application is designed to
operate only under similar hardware and/or software environments.
3. Needs of multiple sites were considered in the design, and the application is designed to
operate under different hardware and/or software environments.
4. Documentation and support plan are provided and tested to support the application at
multiple sites and the application is as described by 1 or 2.
5. Documentation and support plan are provided and tested to support the application at
multiple sites and the application is as described by 3.
1
Facilitate Changes

Was the application specifically designed, developed, and supported to facilitate change?
Facilitate Change describes the degree to which the application has been developed for easy modification of processing logic or data structure.

The following characteristics can apply for the application:
· Flexible query and report facility is provided that can handle simple requests;
for example, and/or logic applied to only one internal logical file.
· Flexible query and report facility is provided that can handle requests of average complexity,
for example, and/or logic applied to more than one internal logical file.
· Flexible query and report facility is provided that can handle complex requests,
for example, and/or logic combinations on one or more internal logical files.
· Business control data is kept in tables that are maintained by the user with online interactive processes, but
changes take effect only on the next business day.
· Business control data is kept in tables that are maintained by the user with online interactive processes, and
the changes take effect immediately.

Score As Descriptions To Determine Degree of Influence:
0. None of the above.
1. A total of one item from above.
2. A total of two items from above.
3. A total of three items from above.
4. A total of four items from above.
5. A total of five items from above.


1


Now using the GSC we can calculate VAF and then we can achive Adjusted FP

2009-12-04

Estimation using Fuction Point Analysis-EIF,ILF(Part 3)

What is External Interface File(EIF):

EIF is a user-indentifiable logically related data which is utilized by the applicatin but maintained by some other application.They are not maintained by the application.
For example,if you are using credit card information,or using some kind of payment gateway that are only referencing and application don't have the control directly,then this file ise a EIF.

Complexity Table of EIF:
It depends on two things:
-Record Element type(RET):They are logical sub groupings of DET from user view point.If there is no logical grouping of data then we consider it as one RET. In the following context there are several phone number for a customer,but they are logically grouping.

-Data Element Type(DET):Counting of DET doesn't change for EIF,EI,EO,EQ .


EIF complexity table:


What is Internal Logical File(ILF):
An ILF is a user identifiable group of logically related data maintained by the application.
Application have directly control on ILF.
Identify ILF's:
Stored internal to the application
Maintained through a standarized process of application.
User identified.
Temp file are not count as ILF's.

In the above context if your client thing that there is only one phone number for a customer but still you have maintained it in two tables for scale up your application,then you have to count 1 ILF ,but if a customer has multiple phone number and you require two table(master & details) then the ILF should be 2.

Complexity of ILF: It depends on two things:
-Record Element type(RET)
-Data Element Type(DET)
Complexity Table of ILF:

2009-12-03

Estimation using Fuction Point Analysis-EO,EQ(Part 2)


What is External Output(EO)?
External Output(EO)-EO's are functions which manipulate data and present to the user.
Manipulation means derived and calculated informaton.
Some of real time EO examples are(becuse it need complex query along with the calculation) -
-Balance sheet report
-Customer monthly statement
-Complex graphical charts like bar chart ,pie chart etc.
If the same EO data is produced on two different media output should be counted as two EO's.In short if the same data is sent on a web page and also on a mobile will be counted as 2 EO's.
Graphical output of data in Pie chart ,bar chart etc should be counted as EO's.
If a report is generated by report generator it should be counted as EO.One EI should be counted for each report command like search ,sort ,merge etc generated by report generator.

What are not EO's?
ADHOC reporting where the end user can fire SQL and generate report is not a EO.For example ,if you have made a simple query window where the end user can fire and get the data are not EO.
Two report showing the different data with same processing logic (suppose one query output is ascending order and another is descending order)should be counted as on EO

Complexity of EO:
Like EI,Complexity of EO is depends on File type reference(FTR) and Data element type(DET)
DET are fields and attributes.
DET should be unique and user recognizable.
Count DET for each parameter in the report.Suppose you are generating reports based on the user input i.e Cust ID and Cust Name,then the DTE is 2
Count DET for each numerical value in a graphical output.Suppose you are showing graph which showing percentage value or other numeric value,you need to count the DET.
Count DET for summary and totalling fields.Suppose yoy are showing each month summery profit and total year profit ,then you should count 1 DET.
Complexity Table for EO:
Like EI,you can determine the complexity of EO from the Complexity table of EO as follows-


What is External Quaries(EQ):
EQ is a unique request for retrieving data.
EQ does not update any ILF's or EIF's.
EQ doesnot contain derived data it simply retrieves the information where EO retrives complex calculated data.Suppose in customer screen ,customer dropdown is EO because it direct fetch data from Customer Master table.

Example of EQ:
Dynamic dropdown or list display
Simple reports displayed from a single table without data manipulation
Section of data retrieval based on input.
Different graphical display request by a user should be counted as EQ.
Help functionality which displays help text or field sensitive help will be counted as one EQ Perscreen.Suppose you have a screen where F1 key press shows the help,then the EQ will be 1 for that.

Complexity of EO: Like EI,EO,Complexity of EQ is depends on File type reference(FTR) and Data element type(DET)

Complexity Table for EQ:

But remember for complex Query ,calculated output you should consider EO and for simple query you should consider EQ(EQ just go for one ILF and displays information)

Estimation using Fuction Point Analysis-EI(Part 1)

Fuction point is a unit of measurefor software size based on user requirements(not the internal process i.e we should not consider the internal complexity or workflow,only consider the user requirement).It was developed by Mr.Allan Albrecht at IBM in the late 1970s,as an alternative of line of code.(line of code has some limitations like its vary language to language and its difficult to predict).

Software measure is a numerical value assigned to a software project depending on the complexity of project.The complexity of software can be known from "Data Collected" and "ClientArtifacts".It can be-
1)Function Points
2)Use case points
3)Lines of code
and convert to Man days,Man month or Man hours numerical values.


The objective of this tutorial is how to calculate this Function point and arrive to Man days so that you can give a proposal to a client.

First see what are the different operations a user does with an application-


The major element of Function point analysis is Application boundaries.There are two Application boundaries-
-1.Internal:Data which is maintained and directly controlled by application(ILF)
-2.External:When data is referenced to external entities(EIF)
The more you have external application boundary the more complexity.So first differentiate the application boundary before FPA.

Now come to the rest of the elements like EI,EO,EQ,EIF and ILF etc.
EI(External Input)-EI moves the data in to the application from external app boundary to internal boundary.EI mainly updates ILF information.
For every add/update and delete count one EI
Every input screen is not a EI.i.e Query screen ,login screen,menus reports screen cannot be counted as EI even there is a user input.
Process that maintain ILF like windows process or batch process that update database should be counted as EI.

EI has two attributes which basically define the complexity of EI
-1.File type reference(FTR):
FTR is a file or data referenced by EI.
Count 1 FTR for every ILF maintained.
Count 1 FTR for every ILF referenced.
Count 1 FTR for every EIF referenced.

-2.Data element type(DET):
DET are fields and attributes.In the above customer screen Customer code,Customer Name are fields or attributes ,so these are DETs.
DET should be unique and user recognizable.If the customer screen comes again for another operation from another menu we should not count DET.
Foreign keys are also DET's.Suppose customer ID is foreign key of address table ,then this foreign key should be counted as DET.
Auto generated fields are also counted as DET as they are maintained in the ILF.Because we have to write seperate logic to create autogenerate numbers.
Duplicate fields populated by the same user input should be counted as one DET.
Error message are counted as DET.


So In this example there is 12 DET and 3 FTR,So from EI rating table 6 is a complexity level of customer screen
If we consider, 3 is a simple,4 is a medium and 6 is a complex,then from EI complexity table we can get the complexity value "complex" for this Customer screen

2009-12-01

Tutorial 15:Encapsulation

Tutorial 14:Exception Handling

Exceptions are unforeseen errors that happen in your programs. Most of the time, you can, and should, detect and handle program errors in your code. For example, validating user input, checking for null objects, and verifying the values returned from methods are what you expect, are all examples of good standard error handling that you should be doing all the time.
using System;
using System.IO;

class FinallyDemo
{
static void Main(string[] args)
{
FileStream outStream = null;
FileStream inStream = null;

try
{
outStream = File.OpenWrite("DestinationFile.txt");
inStream = File.OpenRead("BogusInputFile.txt");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (outStream != null)
{
outStream.Close();
Console.WriteLine("outStream closed.");
}
if (inStream != null)
{
inStream.Close();
Console.WriteLine("inStream closed.");
}
}
}
}

Tutorial 13:Events

An event is a member that enables an object or class to provide notifications.
As compared to delegates events works with source and listener methodology. So listeners who are interested in receiving some events they subscribe to the source. Once this subscription is done the source raises events to its entire listener when needed. One source can have multiple listeners.
In C# events are based on delegates, with the originator defining one or more call back functions. A call back function is a function in which one piece of code defines another implements, in other words, one piece of code says, “If you implement a function which looks like this, I can call it”. A class that wants to sue events defines callback functions or delegates, and the listening object then implements them.
Events have no return type.
There are following two differences:
1. Events use delegates.
2. Delegates are function pointers they can move across any client.

// File name : events.cs
using System;
namespace CSharp.AStepAhead.events
{
class Button
{
public event EventHandler Click;
public void Reset()
{
Click = null;
}
}
public class impButton
{
Button Button1 = new Button();
public impButton()
{
Button1.Click += new EventHandler(Button1_Click);
}
public void Connect()
{
Console.WriteLine("Attaching the event handler");
Button1.Click += new EventHandler(Button1_Click);
}
void Button1_Click(object s, EventArgs e)
{
Console.WriteLine("Button1 clicked!");
}
public void Disconnect()
{
Console.WriteLine("Removng the event handler");
Button1.Click -= new EventHandler(Button1_Click);
}
static void Main()
{
impButton objButton = new impButton();
objButton.Connect();
Console.ReadLine();
objButton.Disconnect();
Console.ReadLine();
}
}
}

Tutorial 12:Delegates

A delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time.
when you want to create a delegate in C# you make use of delegate keyword.

The name of your delegate can be whatever you desire. However, you must define the delegate to match the signature of the method it will point to. fo example the following delegate can point to any method taking two integers and returning an integer.

public delegate int DelegateName(int x, int y);

A Delegate Usage Example

namespace MyFirstDelegate
{
//This delegate can point to any method,
//taking two integers and returning an
//integer.
public delegate int MyDelegate(int x, int y);
//This class contains methods that MyDelegate will point to.
public class MyClass
{
public static int Add(int x, int y)
{
return x + y;
}
public static int Multiply(int x, int y)
{
return x * y;
}
}
class Program
{
static void Main(string[] args)
{
//Create an Instance of MyDelegate
//that points to MyClass.Add().
MyDelegate del1 = new MyDelegate(MyClass.Add);
//Invoke Add() method using the delegate.
int addResult = del1(5, 5);
Console.WriteLine("5 + 5 = {0}\n", addResult);
//Create an Instance of MyDelegate
//that points to MyClass.Multiply().
MyDelegate del2 = new MyDelegate(MyClass.Multiply);
//Invoke Multiply() method using the delegate.
int multiplyResult = del2(5, 5);
Console.WriteLine("5 X 5 = {0}", multiplyResult);
Console.ReadLine();
}
}
}
Delegate ability to Multicast
Delegate's ability to multicast means that a delegate object can maintain a list of methods to call, rather than a single method
if you want to add a method to the invocation list of a delegate object , you simply make use of the overloaded += operator, and if you want to remove a method from the invocation list you make use of the overloaded operator -= .
Note: The Multicast delegate here contain methods that return void, if you want to create a multicast delegate with return type you will get the return type of the last method in the invocation list.
A Multicast Delegate Example
namespace MyMulticastDelegate
{
//this delegate will be used to call more than one
//method at once
public delegate void MulticastDelegate(int x, int y);
//This class contains methods that MyDelegate will point to.
public class MyClass
{
public static void Add(int x, int y)
{
Console.WriteLine("You are in Add() Method");
Console.WriteLine("{0} + {1} = {2}\n", x, y, x + y);
}
public static void Multiply(int x, int y)
{
Console.WriteLine("You are in Multiply() Method");
Console.WriteLine("{0} X {1} = {2}", x, y, x * y);
}
}
class Program
{
static void Main(string[] args)
{
//Create an Instance of MulticastDelegate
//that points to MyClass.Add().
MulticastDelegate del = new MulticastDelegate(MyClass.Add);
//using the same instance of MulticastDelegate
//to call MyClass.Multibly() by adding it to it's
//invocation list.
del += new MulticastDelegate(MyClass.Multiply);
//Invoke Add() and Multiply() methods using the delegate.
//Note that these methods must have a void return vlue
Console.WriteLine("****calling Add() and Multibly() Methods.****\n\n");
del(5, 5);
//removing the Add() method from the invocation list
del -= new MulticastDelegate(MyClass.Add);
Console.WriteLine("\n\n****Add() Method removed.****\n\n");
//this will invoke the Multibly() method only.
del(5, 5);
}
}
}

Tutorial 11:Interfaces

An interface looks like a class, but has no implementation. The only thing it contains are definitions of events, indexers, methods and/or properties.

Defining an Interface: MyInterface.cs

interface IMyInterface
{
void MethodToImplement();
}

Using an Interface: InterfaceImplementer.cs

class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}

public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}

Interface Inheritance
using System;

interface IParentInterface
{
void ParentInterfaceMethod();
}

interface IMyInterface : IParentInterface
{
void MethodToImplement();
}

class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
iImp.ParentInterfaceMethod();
}

public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}

public void ParentInterfaceMethod()
{
Console.WriteLine("ParentInterfaceMethod() called.");
}
}

Tutorial 10:Indexers

C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C# community. Defining a C# indexer is much like defining properties. We can say that an indexer is a member that enables an object to be indexed in the same way as an array.

this [argument list]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}

Where the modifier can be private, public, protected or internal. The return type can be any valid C# types. The 'this' is a special keyword in C# to indicate the object of the current class. The formal-argument-list specifies the parameters of the indexer. The formal parameter list of an indexer corresponds to that of a method, except that at least one parameter must be specified, and that the ref and out parameter modifiers are not permitted. Remember that indexers in C# must have at least one parameter. Other wise the compiler will generate a compilation error.
The following program shows a C# indexer in action

// C#: INDEXER

using System;
using System.Collections;

class MyClass
{
private string []data = new string[5];
public string this [int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
}


class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc[0] = "Rajesh";
mc[1] = "A3-126";
mc[2] = "Snehadara";
mc[3] = "Irla";
mc[4] = "Mumbai";
Console.WriteLine("{0},{1},{2},{3},{4}",mc[0],mc[1],mc[2],mc[3],mc[4]);
}
}

The indexers in C# can be overloaded just like member functions. The formal parameter list of an indexer defines the signature of the indexer. Specifically, the signature of an indexer consists of the number and types of its formal parameters. The element type is not part of an indexer's signature, nor is the names of the formal parameters. The signature of an indexer must differ from the signatures of all other indexers declared in the same class. C# do not have the concept of static indexers. If we declare an indexer static, the compiler will show a compilation time error.