Just another WordPress.com site

You can select multiple row from single row of two dates.

Table Data:

ID                      STARTDATE                   ENDDATE

1                         01/04/2013                      04/04/2013

2                          25/12/2013                      27/12/2013

 

Output:

ID                     DATE

1                       01/04/2013

1                      02/04/2013

1                       03/04/2013

1                      04/04/2013

2                      25/12/2013

2                      26/12/2013

2                      27/12/2013

 

Answer:

;with cte as (
select ID, START_DATE, END_DATE
from TABLENAME
union all
select t.ID, dateadd(dd,1,cte.START_DATE) START_DATE, t.END_DATE
from cte
join TBL_AT_ONDUTY_RECORD t on cte.ID = t.ID and cte.END_DATE >=dateadd(dd,1,cte.START_DATE)
where t.ON_STATUS=’S’
)
select * from cte order by ID,START_DATE option (maxrecursion 32000)

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”SatishPatelLogic.aspx.cs” Inherits=”SatishPatelLogic”  %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head id=”Head1″ runat=”server”>
<title>Satish Patel Property and Bussiness Logic Generator</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<table cellpadding=”1″ cellspacing=”2″ border=”0″ width=”100%”>
<tr>
<td style=”width: 594px; height: 47px;”>
<h2> Generate Property and Bussiness Logic</h2></td>
<td style=”height: 47px”></td>
</tr>
<tr>
<td style=”width: 594px”>
<asp:Label ID=”LblMsg” runat=”server” Font-Bold=”True” ForeColor=”Red”></asp:Label></td>
<td>
</td>
</tr>
<tr>
<td style=”width: 594px”>
<strong><span style=”color: #003333″>Enter The Connection String</span></strong><asp:TextBox ID=”TextBox1″ runat=”server” Width=”615px” Height=”51px”></asp:TextBox></td>
<td>
<br />
<asp:Button ID=”BtnSend” runat=”server” OnClick=”BtnSend_Click” Text=”Send” /></td>
</tr>
<tr>
<td style=”width: 594px”></td>
<td></td>
</tr>
<tr>
<td style=”width: 594px”>
<strong><span style=”color: #003366″>Enter The Path (Save to Perfect Path of Property)</span></strong><asp:TextBox ID=”TxtProperty” runat=”server” Height=”51px” Width=”615px”></asp:TextBox></td>
<td>
Namespace:<asp:TextBox ID=”TxtNamespace” runat=”server”></asp:TextBox></td>
</tr>
<tr>
<td style=”width: 594px”>
<strong><span style=”color: #003366″>Enter The Path (Save to Perfect Path of Bussiness
Logic)</span></strong><asp:TextBox ID=”TxtBussiness” runat=”server” Height=”51px” Width=”615px”></asp:TextBox></td>
<td>
</td>
</tr>
<tr>
<td style=”width: 594px”></td>
<td></td>
</tr>
<tr>
<td style=”width: 594px”></td>
<td></td>
</tr>
<script language=”javascript” type=”text/javascript”>
function checkAllBoxes(){

//get total number of rows in the gridview and do whatever
//you want with it..just grabbing it just cause
var totalChkBoxes = parseInt(‘<%= GVDatabase.Rows.Count %>’);
var gvControl = document.getElementById(‘<%= GVDatabase.ClientID %>’);

//this is the checkbox in the item template…this has to be the same name as the ID of it
var gvChkBoxControl = “chkBoxChild”;

//this is the checkbox in the header template
var mainChkBox = document.getElementById(“chkBoxAll”);

//get an array of input types in the gridview
var inputTypes = gvControl.getElementsByTagName(“input”);

for(var i = 0; i < inputTypes.length; i++)
{
//if the input type is a checkbox and the id of it is what we set above
//then check or uncheck according to the main checkbox in the header template
if(inputTypes[i].type == ‘checkbox’ && inputTypes[i].id.indexOf(gvChkBoxControl,0) >= 0)
inputTypes[i].checked = mainChkBox.checked;
}
}
</script>
<tr>
<td colspan=”2″>
<asp:GridView ID=”GVDatabase” runat=”server” AutoGenerateColumns=”False” Width=”361px”>
<Columns>
<asp:TemplateField HeaderText=”Check”>
<ItemTemplate>
<asp:CheckBox ID=”chkBoxChild” runat=”server” />
</ItemTemplate>
<HeaderTemplate>
<input id=”chkBoxAll” type=”checkbox” onclick=”checkAllBoxes()” />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Table Name”>
<ItemTemplate>
<asp:Label ID=”LblTableName” runat=”server” Text='<%# Bind(“name”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”id”>
<ItemTemplate>
<asp:Label ID=”Label2″ runat=”server” Text='<%# Bind(“id”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>

<tr>
<td colspan=”2″>
<asp:Button ID=”BtnCreate” runat=”server” OnClick=”BtnCreate_Click” Text=”Save” EnableTheming=”True” /></td>
</tr>
</table>
<br />
<br />
&nbsp;<br />
<br />
&nbsp;<br />
<br />

<br />
<br />
<br />
&nbsp;</div>
</form>
</body>
</html>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;
using System.IO;
public partial class SatishPatelLogic : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Text = System.Configuration.ConfigurationManager.AppSettings[“SqlServerConnectionString”].ToString();
}
}
protected void BtnSend_Click(object sender, EventArgs e)
{
BindData();
}
private void BindData()
{
SqlConnection con = new SqlConnection(TextBox1.Text.Trim());
con.Open();
String str = “SELECT * FROM dbo.sysobjects WHERE xtype=’U'”;
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
adp.Fill(ds);
GVDatabase.DataSource = ds;
GVDatabase.DataBind();
}
protected void BtnCreate_Click(object sender, EventArgs e)
{
foreach (GridViewRow r in GVDatabase.Rows)
{
CheckBox ChkSelect = (CheckBox)r.FindControl(“chkBoxChild”);
if (ChkSelect.Checked == true)
{
Label LblTableName = (Label)r.FindControl(“LblTableName”);
CreateData(LblTableName.Text);
}
else
{
}
}
}
private void CreateData(String tablename)
{
try
{

SqlConnection con = new SqlConnection(TextBox1.Text.Trim());
con.Open();
String str = “select COLUMN_NAME,DATA_TYPE,CHARACTER_OCTET_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = ‘” + tablename + “‘”;
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
// Create Property generate.

StringBuilder sb = new StringBuilder();

sb.Append(“using System;” + System.Environment.NewLine + “”);
sb.Append(“using System.Data;” + System.Environment.NewLine + “”);
sb.Append(“using System.Configuration;” + System.Environment.NewLine + “”);
sb.Append(“using System.Web;” + System.Environment.NewLine + “”);
//sb.Append(“using System.Web.Security;” + System.Environment.NewLine + “”);
//sb.Append(“using System.Web.UI;” + System.Environment.NewLine + “”);
//sb.Append(“using System.Web.UI.WebControls;” + System.Environment.NewLine + “”);
//sb.Append(“using System.Web.UI.WebControls.WebParts;” + System.Environment.NewLine + “”);
//sb.Append(“using System.Web.UI.HtmlControls;” + System.Environment.NewLine + “”);

sb.Append(“/// <summary>” + System.Environment.NewLine + “”);
sb.Append(“/// Summary description for ” + tablename + “” + System.Environment.NewLine + “”);
sb.Append(“/// </summary>” + System.Environment.NewLine + “”);

sb.Append(“namespace ” + TxtNamespace.Text.Trim() + “.BEL{” + System.Environment.NewLine + “”);

sb.Append(“public class ” + tablename + “” + System.Environment.NewLine + “”);
sb.Append(“{” + System.Environment.NewLine + “”);
sb.Append(“public ” + tablename + “()” + System.Environment.NewLine + “”);
sb.Append(“{” + System.Environment.NewLine + “”);
sb.Append(“//” + System.Environment.NewLine + “”);
sb.Append(“// TODO: Add constructor logic here” + System.Environment.NewLine + “”);
sb.Append(“//” + System.Environment.NewLine + “”);
sb.Append(“}” + System.Environment.NewLine + “”);
sb.Append(” #region VARIABLE of ” + tablename + ” and PROPERTY” + System.Environment.NewLine + “”);

for (int i = 0; ds.Tables[0].Rows.Count > i; i++)
{
String datatype = ds.Tables[0].Rows[i][“DATA_TYPE”].ToString();
String columname = ds.Tables[0].Rows[i][“COLUMN_NAME”].ToString();
if (datatype == “numeric” || datatype == “int” || datatype == “bigint”)
{
sb.Append(“private int _” + columname + “;” + System.Environment.NewLine + “”);
sb.Append(“public int ” + columname + “” + System.Environment.NewLine + “”);
sb.Append(“{” + System.Environment.NewLine + “”);
sb.Append(“get { return (_” + columname + “); }”);
sb.Append(“” + System.Environment.NewLine + “”);
sb.Append(“set { _” + columname + ” = value; }”);
sb.Append(“” + System.Environment.NewLine + “}” + System.Environment.NewLine + “”);
sb.Append(“” + System.Environment.NewLine + “” + System.Environment.NewLine + “”);
}
else if (datatype == “varchar” || datatype == “char” || datatype == “ntext” || datatype == “nvarchar”)
{
sb.Append(“private String _” + columname + “;” + System.Environment.NewLine + “”);
sb.Append(“public String ” + columname + “” + System.Environment.NewLine + “”);
sb.Append(“{” + System.Environment.NewLine + “”);
sb.Append(“get { return (_” + columname + “); }”);
sb.Append(“” + System.Environment.NewLine + “”);
sb.Append(“set { _” + columname + ” = value; }”);
sb.Append(“” + System.Environment.NewLine + “}” + System.Environment.NewLine + “”);
sb.Append(“” + System.Environment.NewLine + “” + System.Environment.NewLine + “”);
}
else if (datatype == “datetime”)
{
sb.Append(“private DateTime _” + columname + “;” + System.Environment.NewLine + “”);
sb.Append(“public DateTime ” + columname + “” + System.Environment.NewLine + “”);
sb.Append(“{” + System.Environment.NewLine + “”);
sb.Append(“get { return (_” + columname + “); }”);
sb.Append(“” + System.Environment.NewLine + “”);
sb.Append(“set { _” + columname + ” = value; }”);
sb.Append(“” + System.Environment.NewLine + “}” + System.Environment.NewLine + “”);
sb.Append(“” + System.Environment.NewLine + “” + System.Environment.NewLine + “”);
}
else
{
sb.Append(“private object _” + columname + “;” + System.Environment.NewLine + “”);
sb.Append(“public object ” + columname + “” + System.Environment.NewLine + “”);
sb.Append(“{” + System.Environment.NewLine + “”);
sb.Append(“get { return (_” + columname + “); }”);
sb.Append(“” + System.Environment.NewLine + “”);
sb.Append(“set { _” + columname + ” = value; }”);
sb.Append(“” + System.Environment.NewLine + “}” + System.Environment.NewLine + “”);
sb.Append(“” + System.Environment.NewLine + “” + System.Environment.NewLine + “”);
}

}
sb.Append(” #endregion” + System.Environment.NewLine + “”);
sb.Append(“}” + System.Environment.NewLine + “”);
sb.Append(“}” + System.Environment.NewLine + “”);
//string strPath = Request.PhysicalApplicationPath
//             + “\\App_Code\\PropertyClasses\\pro_” + tablename + “.cs”;

string strPath = TxtProperty.Text.Trim() + tablename + “.cs”;

FileStream fStream = File.Create(strPath);
fStream.Close();
StreamWriter sWriter = new StreamWriter(strPath);
sWriter.Write(sb);
sWriter.Close();
// end property generate..

// create bussiness logic

StringBuilder sbcb = new StringBuilder();

sbcb.Append(“using System;” + System.Environment.NewLine + “”);
sbcb.Append(“using System.Data;” + System.Environment.NewLine + “”);
sbcb.Append(“using System.Configuration;” + System.Environment.NewLine + “”);
sbcb.Append(“using System.Web;” + System.Environment.NewLine + “”);
sbcb.Append(“using System.Web.Security;” + System.Environment.NewLine + “”);
sbcb.Append(“using System.Web.UI;” + System.Environment.NewLine + “”);
sbcb.Append(“using System.Web.UI.WebControls;” + System.Environment.NewLine + “”);
sbcb.Append(“using System.Web.UI.WebControls.WebParts;” + System.Environment.NewLine + “”);
sbcb.Append(“using System.Web.UI.HtmlControls;” + System.Environment.NewLine + “”);
sbcb.Append(“using System.Collections;” + System.Environment.NewLine + “”);
sbcb.Append(“using System.Data.SqlClient;” + System.Environment.NewLine + “”);
sbcb.Append(“using “+ TxtNamespace.Text.Trim() +”.BEL;” + System.Environment.NewLine + “”);

sbcb.Append(“/// <summary>” + System.Environment.NewLine + “”);
sbcb.Append(“/// Summary description for cls” + tablename + “” + System.Environment.NewLine + “”);
sbcb.Append(“/// </summary>” + System.Environment.NewLine + “”);

sbcb.Append(“namespace ” + TxtNamespace.Text.Trim() + “.BLL{” + System.Environment.NewLine + “”);

sbcb.Append(“public class cls” + tablename + “” + System.Environment.NewLine + “”);
sbcb.Append(“{” + System.Environment.NewLine + “”);

String Mode=”@Mode”;
String valueall=”selectall”;
// get all data
sbcb.Append(“public static DataSet GetAll” + tablename + “()” + System.Environment.NewLine + “”);
sbcb.Append(“{try{AppDB ObjDB = new AppDB();” + System.Environment.NewLine + “”);
sbcb.Append(“SqlDataAdapter DA = new SqlDataAdapter(\”SP_” + tablename + “\”, ObjDB.con);” + System.Environment.NewLine + “”);
sbcb.Append(“DA.SelectCommand.CommandType = CommandType.StoredProcedure;” + System.Environment.NewLine + “”);
sbcb.Append(“DA.SelectCommand.Parameters.AddWithValue(\”” + Mode + “\”, \”” + valueall + “\”);” + System.Environment.NewLine + “”);
sbcb.Append(“DataSet ds = new DataSet();” + System.Environment.NewLine + “”);
sbcb.Append(“ObjDB.OpenDB();DA.Fill(ds);ObjDB.CloseDB();” + System.Environment.NewLine + “”);
sbcb.Append(“return ds;}” + System.Environment.NewLine + “”);

sbcb.Append(“catch (Exception Ex){throw Ex;}}” + System.Environment.NewLine + “”);
// end

for (int j = 0; ds.Tables[0].Rows.Count > j; j++)
{
//    String datatype=ds.Tables[0].Rows[j][“DATA_TYPE”].ToString();
String columname = ds.Tables[0].Rows[j][“COLUMN_NAME”].ToString();

// Create Get Function

if (j == 0)
{
String valuebyid = “selectbyid”;
// get all data
sbcb.Append(“public static DataSet Get” + tablename + “ByID(“+ tablename +” obj”+ tablename +”)” + System.Environment.NewLine + “”);
sbcb.Append(“{try{AppDB ObjDB = new AppDB();” + System.Environment.NewLine + “”);
sbcb.Append(“SqlDataAdapter DA = new SqlDataAdapter(\”SP_” + tablename + “\”, ObjDB.con);” + System.Environment.NewLine + “”);
sbcb.Append(“DA.SelectCommand.CommandType = CommandType.StoredProcedure;” + System.Environment.NewLine + “”);
sbcb.Append(“DA.SelectCommand.Parameters.AddWithValue(\”@” + columname + “\”, obj” + tablename + “.” + columname + “);” + System.Environment.NewLine + “”);
sbcb.Append(“DA.SelectCommand.Parameters.AddWithValue(\”” + Mode + “\”, \”” + valuebyid + “\”);” + System.Environment.NewLine + “”);
sbcb.Append(“DataSet ds = new DataSet();” + System.Environment.NewLine + “”);
sbcb.Append(“ObjDB.OpenDB();DA.Fill(ds);ObjDB.CloseDB();” + System.Environment.NewLine + “”);
sbcb.Append(“if (ds.Tables[0].Rows.Count > 0){return ds;}else {return null;}}” + System.Environment.NewLine + “”);

sbcb.Append(“catch (Exception Ex){throw Ex;}}” + System.Environment.NewLine + “”);

String valuedelete = “delete”;

sbcb.Append(“public static bool Delete” + tablename + “(“+ tablename +” obj”+ tablename +”)” + System.Environment.NewLine + “”);
sbcb.Append(“{bool flg = false;try{AppDB ObjDB = new AppDB();” + System.Environment.NewLine + “”);
sbcb.Append(“SqlCommand SC = new SqlCommand(\”SP_” + tablename + “\”, ObjDB.con);” + System.Environment.NewLine + “”);
sbcb.Append(“SC.CommandType = CommandType.StoredProcedure;” + System.Environment.NewLine + “”);
sbcb.Append(“SC.Parameters.AddWithValue(\”@” + columname + “\”, obj” + tablename + “.” + columname + “);” + System.Environment.NewLine + “”);
sbcb.Append(“SC.Parameters.AddWithValue(\”” + Mode + “\”, \”” + valuedelete + “\”);” + System.Environment.NewLine + “”);

sbcb.Append(“ObjDB.OpenDB();” + System.Environment.NewLine + “”);
sbcb.Append(“if (SC.ExecuteNonQuery() > 0)” + System.Environment.NewLine + “”);
sbcb.Append(“flg = true;” + System.Environment.NewLine + “”);
sbcb.Append(“ObjDB.CloseDB();” + System.Environment.NewLine + “”);
sbcb.Append(“}catch (Exception Ex){throw Ex;} return flg;}” + System.Environment.NewLine + “”);

// end
}
else
{
if (j == 1)
{

sbcb.Append(“public static String Add” + tablename + “(“+ tablename +” obj”+ tablename +”)” + System.Environment.NewLine + “”);
sbcb.Append(“{String new”+ tablename +” = \”\”;try{AppDB ObjDB = new AppDB();” + System.Environment.NewLine + “”);
sbcb.Append(“SqlCommand SC = new SqlCommand(\”SP_” + tablename + “\”, ObjDB.con);” + System.Environment.NewLine + “”);
sbcb.Append(“SC.CommandType = CommandType.StoredProcedure;” + System.Environment.NewLine + “”);
sbcb.Append(“SC.Parameters.AddWithValue(\”@” + columname + “\”, obj” + tablename + “.” + columname + “);” + System.Environment.NewLine + “”);

}
else
{
sbcb.Append(“SC.Parameters.AddWithValue(\”@” + columname + “\”, obj” + tablename + “.” + columname + “);” + System.Environment.NewLine + “”);

}
int count = ds.Tables[0].Rows.Count – 1;
if (j == count)
{
String valueinsert = “insert”;
sbcb.Append(“SC.Parameters.AddWithValue(\”” + Mode + “\”, \”” + valueinsert + “\”);” + System.Environment.NewLine + “”);

sbcb.Append(“ObjDB.OpenDB();” + System.Environment.NewLine + “”);
sbcb.Append(“Object objs = SC.ExecuteScalar();” + System.Environment.NewLine + “”);
sbcb.Append(” if (objs != null){new” + tablename + ” = Convert.ToString(objs);}” + System.Environment.NewLine + “”);
sbcb.Append(“ObjDB.CloseDB();” + System.Environment.NewLine + “”);
sbcb.Append(“}catch (Exception Ex){throw Ex;} return new” + tablename + “;}” + System.Environment.NewLine + “”);

}
}

}

// update for logic

for (int k = 0; ds.Tables[0].Rows.Count > k; k++)
{
//    String datatype=ds.Tables[0].Rows[j][“DATA_TYPE”].ToString();
String columname = ds.Tables[0].Rows[k][“COLUMN_NAME”].ToString();

// Create Get Function

if (k == 0)
{
sbcb.Append(“public static bool Update” + tablename + “(” + tablename + ” obj” + tablename + “)” + System.Environment.NewLine + “”);
sbcb.Append(“{bool flg = false;try{AppDB ObjDB = new AppDB();” + System.Environment.NewLine + “”);
sbcb.Append(“SqlCommand SC = new SqlCommand(\”SP_” + tablename + “\”, ObjDB.con);” + System.Environment.NewLine + “”);
sbcb.Append(“SC.CommandType = CommandType.StoredProcedure;” + System.Environment.NewLine + “”);
sbcb.Append(“SC.Parameters.AddWithValue(\”@” + columname + “\”, obj” + tablename + “.” + columname + “);” + System.Environment.NewLine + “”);

// end
}
else
{

sbcb.Append(“SC.Parameters.AddWithValue(\”@” + columname + “\”, obj” + tablename + “.” + columname + “);” + System.Environment.NewLine + “”);

int count = ds.Tables[0].Rows.Count – 1;
if (k == count)
{
String valueupdate = “update”;
sbcb.Append(“SC.Parameters.AddWithValue(\”” + Mode + “\”, \”” + valueupdate + “\”);” + System.Environment.NewLine + “”);

sbcb.Append(“ObjDB.OpenDB();” + System.Environment.NewLine + “”);
sbcb.Append(“if (SC.ExecuteNonQuery() > 0)” + System.Environment.NewLine + “”);
sbcb.Append(”         flg = true;” + System.Environment.NewLine + “”);
sbcb.Append(“ObjDB.CloseDB();” + System.Environment.NewLine + “”);
sbcb.Append(“}catch (Exception Ex){throw Ex;} return flg;}” + System.Environment.NewLine + “”);

}
}

}

sbcb.Append(“}” + System.Environment.NewLine + “”);
sbcb.Append(“}” + System.Environment.NewLine + “”);
//string strPath1 = Request.PhysicalApplicationPath
//             + “\\App_Code\\BusinessAccessLayer\\BAL_” + tablename + “.cs”;

string strPath1 = TxtBussiness.Text.Trim() + “cls” + tablename + “.cs”;
//   + “\\App_Code\\BusinessAccessLayer\\BAL_” + tablename + “.cs”;

FileStream fStream1 = File.Create(strPath1);
fStream1.Close();
StreamWriter sWriter1 = new StreamWriter(strPath1);
sWriter1.Write(sbcb);
sWriter1.Close();

// create a store procedure
StringBuilder sbsp = new StringBuilder();
sbsp.Append(“– =============================================” + System.Environment.NewLine + “”);
sbsp.Append(“– Author:        <Author,,Viral Patel>” + System.Environment.NewLine + “”);
sbsp.Append(“– Create date: <” + System.DateTime.Now.Date.ToShortDateString() + “>” + System.Environment.NewLine + “”);
sbsp.Append(“– Description:    <” + tablename + “>” + System.Environment.NewLine + “”);
sbsp.Append(“– =============================================” + System.Environment.NewLine + “”);

sbsp.Append(“CREATE PROCEDURE [dbo].[SP_” + tablename + “]” + System.Environment.NewLine + “”);
sbsp.Append(“– Add the parameters for the stored procedure here” + System.Environment.NewLine + “”);

StringBuilder allfieldname = new StringBuilder();
StringBuilder allvaluename = new StringBuilder();
StringBuilder allfieldvalue = new StringBuilder();

StringBuilder firstidnamevalue = new StringBuilder();
StringBuilder selectvalue = new StringBuilder();

for (int x = 0; ds.Tables[0].Rows.Count > x; x++)
{
String columnamess = ds.Tables[0].Rows[x][“COLUMN_NAME”].ToString();
String datatypess = ds.Tables[0].Rows[x][“DATA_TYPE”].ToString();
String lengths = ds.Tables[0].Rows[x][“CHARACTER_OCTET_LENGTH”].ToString();

if (lengths == “”)
{
sbsp.Append(“@” + columnamess + ” ” + datatypess + “=null,” + System.Environment.NewLine + “”);
}
else
{
sbsp.Append(“@” + columnamess + ” ” + datatypess + “(” + lengths + “)=null,” + System.Environment.NewLine + “”);
}
int countsp = ds.Tables[0].Rows.Count – 1;
if (x == countsp)
{
sbsp.Append(“@Mode varchar(100)=null” + System.Environment.NewLine + “”);
sbsp.Append(“AS” + System.Environment.NewLine + “”);
sbsp.Append(“BEGIN” + System.Environment.NewLine + “”);
sbsp.Append(“SET NOCOUNT ON;” + System.Environment.NewLine + “”);

sbsp.Append(“if @Mode=’selectall'” + System.Environment.NewLine + “”);
sbsp.Append(“begin” + System.Environment.NewLine + “”);
sbsp.Append(“Select * from “+ tablename +”” + System.Environment.NewLine + “”);
sbsp.Append(“end” + System.Environment.NewLine + “”);

sbsp.Append(“if @Mode=’selectactive'” + System.Environment.NewLine + “”);
sbsp.Append(“begin” + System.Environment.NewLine + “”);
sbsp.Append(“Select * from “+ tablename +” where Status=’A'” + System.Environment.NewLine + “”);
sbsp.Append(“end” + System.Environment.NewLine + “”);

}

if (x == countsp)
{
allfieldname.Append(“” + columnamess + “”);
allvaluename.Append(“@” + columnamess + “”);
allfieldvalue.Append(“” + columnamess + “=@” + columnamess + “”);
}
else
{
allfieldname.Append(“” + columnamess + “,”);
allvaluename.Append(“@” + columnamess + “,”);
if (x != 0)
{
allfieldvalue.Append(“” + columnamess + “=@” + columnamess + “,”);
}

if (x == 0)
{
firstidnamevalue.Append(“” + columnamess + “=@” + columnamess + “”);
selectvalue.Append(“@” + columnamess + “”);
}
}

}

for (int y = 0; ds.Tables[0].Rows.Count > y; y++)
{
String columnamess = ds.Tables[0].Rows[y][“COLUMN_NAME”].ToString();
String datatypess = ds.Tables[0].Rows[y][“DATA_TYPE”].ToString();
String lengths = ds.Tables[0].Rows[y][“CHARACTER_OCTET_LENGTH”].ToString();

if (y == 0)
{
sbsp.Append(“if @Mode=’selectbyid'” + System.Environment.NewLine + “”);
sbsp.Append(“begin” + System.Environment.NewLine + “”);
sbsp.Append(“Select * from ” + tablename + ” where “+ columnamess +”=@” + columnamess + “” + System.Environment.NewLine + “”);
sbsp.Append(“end” + System.Environment.NewLine + “”);

sbsp.Append(“if @Mode=’delete'” + System.Environment.NewLine + “”);
sbsp.Append(“begin” + System.Environment.NewLine + “”);
sbsp.Append(“Delete from ” + tablename + ” where ” + columnamess + “=@” + columnamess + “” + System.Environment.NewLine + “”);
sbsp.Append(“end” + System.Environment.NewLine + “”);

sbsp.Append(“if @Mode=’insert'” + System.Environment.NewLine + “”);
sbsp.Append(“begin” + System.Environment.NewLine + “”);
sbsp.Append(“insert into ” + tablename + ” (” + allfieldname + “)values(” + allvaluename + “)” + System.Environment.NewLine + “”);
sbsp.Append(“end” + System.Environment.NewLine + “”);

sbsp.Append(“if @Mode=’update'” + System.Environment.NewLine + “”);
sbsp.Append(“begin” + System.Environment.NewLine + “”);
sbsp.Append(“Update ” + tablename + ” Set ” + allfieldvalue + ” where ” + firstidnamevalue + “” + System.Environment.NewLine + “”);
sbsp.Append(“end” + System.Environment.NewLine + “”);

}

int countsps = ds.Tables[0].Rows.Count – 1;
if (y == countsps)
{
sbsp.Append(“select “+ selectvalue +”” + System.Environment.NewLine + “”);
sbsp.Append(“END” + System.Environment.NewLine + “”);
}

}

string strPath2 = TxtBussiness.Text.Trim() + tablename + “.txt”;
//   + “\\App_Code\\BusinessAccessLayer\\BAL_” + tablename + “.cs”;

FileStream fStream2 = File.Create(strPath2);
fStream2.Close();
StreamWriter sWriter2 = new StreamWriter(strPath2);
sWriter2.Write(sbsp);
sWriter2.Close();

// end
// end bussiness logic..
LblMsg.Text = “Creat is successfully.”;

}
}
catch (Exception)
{

throw;
}
}
}

 

 

 

GO

CREATE TABLE [dbo].[Category](
[CatId] [int] IDENTITY(1,1) NOT NULL,
[CategoryName] [nvarchar](50) NULL,
[CategoryLevel] [int] NULL,
[ParentId] [int] NULL,
CONSTRAINT [PK_Category] PRIMARY KEY CLUSTERED
(
[CatId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

declare @CatID int = 1
;WITH cte AS
(
SELECT a.CatId, a.parentId, a.Categoryname, a.CategoryLevel
FROM Category a
WHERE a.CatID = @CatID
UNION ALL
SELECT a.catId, a.parentid, a.Categoryname,a.CategoryLevel
FROM Category a JOIN cte c ON a.parentId = c.CatId
)
SELECT ParentId, CatId, CategoryName,CategoryLevel
FROM cte
order by CategoryLevel,CatID

In 3 Tier Architecture there are following layers.

1) Data Access Layer

2) Business Access Layer

3) Presentation Layer

First of all create  project for Asp.net Web application  for presantiaon layer and then Add two new project ” Class Library” for Business and Data Access Layer. You can See Screen below.

1) Now First We go Data Access Layer with Example.

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace DAL
{
public class Studnet_DAL
{
SqlConnection con;
SqlCommand cmd;
DataSet ds;

public SqlConnection getconnaction()
{
SqlConnection con = new SqlConnection();

con.ConnectionString = ConfigurationManager.ConnectionStrings[“constar”].ToString();
return con;

}

public SqlCommand getcommagnd(string spname)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = getconnaction();
cmd.Connection.Open();

cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = spname;
return cmd;
}

public string insert_update_delte(string sp_name, ArrayList objarry)
{
cmd = new SqlCommand();
SqlParameter iparam = new SqlParameter();

try
{
cmd = getcommagnd(sp_name);

foreach (paramater_user parmuser in objarry)
{
cmd.Parameters.Add(new SqlParameter(“@” + parmuser.parmname, parmuser.pramvalue));
}

iparam.DbType = DbType.Int32;
iparam.Direction = ParameterDirection.ReturnValue;
iparam.ParameterName = “@return”;
cmd.Parameters.Add(iparam);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{

throw ex;
}
return iparam.Value.ToString();
}

public DataSet select_DAL(string sp_name, ArrayList objarry)
{
ds = new DataSet();
cmd = new SqlCommand();

try
{
cmd = getcommagnd(sp_name);
if (objarry != null && objarry.Count > 0)
{
foreach (paramater_user parameter in objarry)
{
if (parameter.pramvalue == null)
{
parameter.pramvalue = null;
}

cmd.Parameters.Add(new SqlParameter(“@” + parameter.parmname, parameter.pramvalue));

}
}

SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds;

}
catch (Exception ex)
{
}
return ds;
}

}

public class paramater_user
{

private string m_userName;
public string parmname
{
get { return m_userName; }
set { m_userName = value; }
}

private object m_userValue;
public object pramvalue
{
get { return m_userValue; }
set { m_userValue = value; }

}

public paramater_user(string name, object value)
{
m_userName = name;
m_userValue = value;
}
}

}

2) Business Access Layer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DAL;
using System.Collections;
using PropertyClass;

namespace BAL
{
public class Student_BAL
{
Student_DAL pro_Student_DAL;
ArrayList obj_ArrayList;
public DataSet Bal_Select(string mode, Pro_tbl_Student obj_Pro_tbl_Student)
{
pro_Student_DAL = new Student_DAL();
obj_ArrayList = new ArrayList();

obj_ArrayList.Add(new Parameter_User(“StringMode”,mode));
obj_ArrayList.Add(new Parameter_User(“EMP_ID”, obj_Pro_tbl_Student.Pro_Emp_Id));
return pro_Student_DAL.DAL_Select(“sp_Employee”, obj_ArrayList);
}

public string bal_Insert_update_delete(string mode, Pro_tbl_Student obj_Pro_tbl_Student)
{
pro_Student_DAL = new Student_DAL();
obj_ArrayList = new ArrayList();

obj_ArrayList.Add(new Parameter_User(“StringMode”, mode));
obj_ArrayList.Add(new Parameter_User(“EMP_ID”, obj_Pro_tbl_Student.Pro_Emp_Id));
obj_ArrayList.Add(new Parameter_User(“EMP_NAME”, obj_Pro_tbl_Student.Pro_Emp_Name));
obj_ArrayList.Add(new Parameter_User(“EMP_Address”, obj_Pro_tbl_Student.pro_Emp_Address));
return pro_Student_DAL.DAL_Insert_Update_Delete(“sp_Employee”,obj_ArrayList);
}

public string bal_Insert_update_delete_Department(string mode, Pro_tbl_Student obj_Pro_tbl_Student, string[] Department)
{
string flag;
pro_Student_DAL = new Student_DAL();
obj_ArrayList = new ArrayList();

obj_ArrayList.Add(new Parameter_User(“StringMode”, mode));
obj_ArrayList.Add(new Parameter_User(“EMP_ID”, obj_Pro_tbl_Student.Pro_Emp_Id));
obj_ArrayList.Add(new Parameter_User(“EMP_NAME”, obj_Pro_tbl_Student.Pro_Emp_Name));
obj_ArrayList.Add(new Parameter_User(“EMP_Address”, obj_Pro_tbl_Student.pro_Emp_Address));
return flag = pro_Student_DAL.DAL_Insert_Update_Delete(“sp_Employee”, obj_ArrayList);

if (flag == “0”)
{

return flag;
}
else
{
for (int i = 0; i < Department.Length; i++)
{
obj_ArrayList.Add(new Parameter_User(“StringMode”, “insert_Dept”));
obj_ArrayList.Add(new Parameter_User(“EMP_ID”, flag));
obj_ArrayList.Add(new Parameter_User(“Department_Name”, Department[i]));
flag = pro_Student_DAL.DAL_Insert_Update_Delete(“sp_Employee”, obj_ArrayList);
obj_ArrayList.Clear();
}
}
}
}
}

=> Property Class.

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

namespace PropertyClass
{
public class Pro_tbl_Student
{
private int Emp_Id;
public int Pro_Emp_Id
{
get { return Emp_Id; }
set { Emp_Id = value; }
}
private string Emp_Name;
public string Pro_Emp_Name
{
get { return Emp_Name;}
set {Emp_Name=value ;}
}

private string Emp_Address;
public string pro_Emp_Address
{
get { return Emp_Address; }
set { Emp_Address = value; }
}

private string Department_Name;
public string Pro_Department_Name
{
get { return Department_Name; }
set { Department_Name = value; }
}
}
}

3) presentation Layer

=> HTML

<%@ Page Title=”Home Page” Language=”C#” MasterPageFile=”~/Site.master” AutoEventWireup=”true”
CodeBehind=”Default.aspx.cs” Inherits=”_3_Tire._Default” %>

<asp:Content ID=”HeaderContent” runat=”server” ContentPlaceHolderID=”HeadContent”>
</asp:Content>
<asp:Content ID=”BodyContent” runat=”server” ContentPlaceHolderID=”MainContent”>

<table width=”100%”>
<tr>
<td style=”width:20%”>
<asp:Label ID=”lblMsg” runat=”server” ></asp:Label> </td>
<td>
&nbsp;</td>
</tr>
<tr>
<td style=”width:20%”>
<asp:Label ID=”lblEmpName” runat=”server” Text=”Employee Name”></asp:Label>
</td>
<td>
<asp:TextBox ID=”txtEmpName” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td style=”width:20%”> <asp:Label ID=”lblEmpAddress” runat=”server” Text=”Employee Address”></asp:Label></td>
<td> <asp:TextBox ID=”txtEmpAddress” runat=”server”></asp:TextBox></td>
</tr>
<tr>
<td style=”width:20%”></td>
<td></td>
</tr>
<tr>
<td style=”width:20%”></td>
<td>
<asp:Button ID=”btnSave” runat=”server” Text=”Save” onclick=”btnSave_Click”
style=”height: 26px” />
<asp:Button ID=”btnCancel” runat=”server” Text=”Cancel” />
</td>
</tr>
<tr>
<td style=”width:20%”>&nbsp;</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td style=”width:20%” colspan=”2″>
<asp:GridView ID=”grdEmployee” runat=”server” AutoGenerateColumns=”false” DataKeyNames=”Emp_ID”>
<Columns>
<asp:BoundField DataField=”Emp_ID” HeaderText=”Employee ID”/>
<asp:BoundField DataField=”EMP_NAME” HeaderText=”Employee Name”/>
<asp:BoundField  DataField=”EMP_ADDRESS” HeaderText=”Employee Address”/>
<asp:TemplateField HeaderText=”Edit”>
<ItemTemplate>
<asp:LinkButton ID=”lbnEdit” runat=”server” OnClick=”lbnEdit_Click” Text=”Edit”>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Delete”>
<ItemTemplate>
<asp:LinkButton ID=”lbnDelete” runat=”server” Text=”Delete” OnClick=”lbnDelete_Click”></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>

</tr>
</table>
</asp:Content>

=>  Student.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PropertyClass;
using BAL;
using System.Data;

namespace _3_Tire
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGridEmp();
}
}

protected void btnSave_Click(object sender, EventArgs e)
{
Pro_tbl_Student obj_Pro_tbl_Student = new Pro_tbl_Student();
Student_BAL obj_Student_BAL = new Student_BAL();
LoadData(obj_Pro_tbl_Student);
string mode = “”;
if (btnSave.Text == “Save”)
{
mode = “insert”;
}
else
{
mode = “update”;
obj_Pro_tbl_Student.Pro_Emp_Id = Convert.ToInt32(ViewState[“EMP_ID”]);
}
string Flag= obj_Student_BAL.bal_Insert_update_delete(mode, obj_Pro_tbl_Student);

if (Flag == “0”)
{
if (mode == “insert”)
{
lblMsg.Text = “Record Save SussessFully”;
}
else
{
lblMsg.Text = “Record Update SussessFully”;
}
FillGridEmp();
ClearControal();
}
else
{
lblMsg.Text = “Record Does not Save Some Error Occur”;
}

btnSave.Text = “Save”;
}

public void ClearControal()
{
txtEmpAddress.Text = “”;
txtEmpName.Text = “”;
}
protected void lbnEdit_Click(object sender,EventArgs e)
{
DataSet ds = new DataSet();
handler(sender,e);
Student_BAL pro_Student_BAL = new Student_BAL();
Pro_tbl_Student obj_Pro_tbl_Student = new Pro_tbl_Student();
string mode = “select”;
obj_Pro_tbl_Student.Pro_Emp_Id=Convert.ToInt32(ViewState[“EMP_ID”]);
ds=pro_Student_BAL.Bal_Select(mode,obj_Pro_tbl_Student);
FillData(ds);
btnSave.Text = “update”;

}
protected void lbnDelete_Click(object sender,EventArgs e)
{
handler(sender,e);
Student_BAL pro_Student_BAL = new Student_BAL();
Pro_tbl_Student obj_Pro_tbl_Student=new Pro_tbl_Student();
string mode = “delete”;
obj_Pro_tbl_Student.Pro_Emp_Id=Convert.ToInt32(ViewState[“EMP_ID”]);
string flag=  pro_Student_BAL.bal_Insert_update_delete(mode, obj_Pro_tbl_Student);
if(flag==”0″)
{
lblMsg.Text = “Record Delete Successfully”;
}
else
{
lblMsg.Text = “There is some Error”;
}

FillGridEmp();
}
public void FillData(DataSet ds)
{
txtEmpName.Text = ds.Tables[0].Rows[0][“EMP_NAME”].ToString();
txtEmpAddress.Text = ds.Tables[0].Rows[0][“EMP_ADDRESS”].ToString();
}
public void handler(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
GridViewRow gvr = btn.NamingContainer as GridViewRow;
string emp_id = grdEmployee.DataKeys[gvr.RowIndex].Value.ToString();
ViewState[“EMP_ID”] = emp_id;
}
public void FillGridEmp()
{
Pro_tbl_Student obj_Pro_tbl_Student = new Pro_tbl_Student();
Student_BAL obj_Student_BAL = new Student_BAL();
DataSet ds = new DataSet();
string mode=””;
mode=”select”;
ds= obj_Student_BAL.Bal_Select(mode,obj_Pro_tbl_Student);
grdEmployee.DataSource = ds;
grdEmployee.DataBind();
grdEmployee.Columns[0].Visible = false;
}

public void LoadData(Pro_tbl_Student obj_Pro_tbl_Student)
{

obj_Pro_tbl_Student.Pro_Emp_Name = txtEmpName.Text;
obj_Pro_tbl_Student.pro_Emp_Address = txtEmpAddress.Text;
}
}
}

 

StoreProcedure

 

 

-- =============================================
-- Author:
-- Create date:
-- Description:
-- =============================================

alter PROCEDURE [dbo].[SP_employee_msunil_three]

-- Add the parameters for the stored procedure here

@ID int=null,
@NAME varchar(50)=null,
@SALARY numeric(18, 0)=null,
--@Dept_id int=null,
@Mode varchar(50)=null,
@deptid int=null,
--@Whereclause varchar(max) = null,

@ID_Out int = 0 output
AS
BEGIN
SET NOCOUNT ON;

declare @str_query varchar(3000)
set @str_query='SELECT id, NAME, salary from EMPLOYEE '

if (@Mode = 'insert') -- INSERT

Begin
BEGIN Transaction
if ((select count(NAME) from EMPLOYEE where NAME=@NAME) > 0)
begin
rollback transaction
return 2
end
else
Begin
insert into EMPLOYEE
(NAME,
SALARY
)

values
(
@NAME,
@SALARY
)

If @@error 0
Begin
rollback transaction
return 1
End
Else
Begin
commit transaction
return 0
End
END

END

if (@Mode = 'update') -- INSERT

Begin

update EMPLOYEE set
NAME=@NAME,
SALARY=@SALARY
where ID=@ID

END

if (@Mode = 'select')
Begin
--Begin Transaction
--exec(@str_query)
--If @@error 0
-- Begin
-- rollback transaction
-- return -1
-- End
--Else
-- Begin
-- commit transaction
-- return 0
-- End
SELECT * from EMPLOYEE

End

if (@Mode = 'delete')
Begin
--Begin Transaction
--exec(@str_query)
--If @@error 0
-- Begin
-- rollback transaction
-- return -1
-- End
--Else
-- Begin
-- commit transaction
-- return 0
-- End
delete from EMPLOYEE where ID=@ID

End

if (@Mode = 'selectgrd')
Begin
--Begin Transaction
--exec(@str_query)
--If @@error 0
-- Begin
-- rollback transaction
-- return -1
-- End
--Else
-- Begin
-- commit transaction
-- return 0
-- End
SELECT * from EMPLOYEE where ID=@ID

End

if (@Mode = 'dept')
Begin
--Begin Transaction
--exec(@str_query)
--If @@error 0
-- Begin
-- rollback transaction
-- return -1
-- End
--Else
-- Begin
-- commit transaction
-- return 0
-- End
SELECT Dept_id,Dept_name from Dept_master

End

if (@Mode = 'selectemployee')
Begin
--Begin Transaction
--exec(@str_query)
--If @@error 0
-- Begin
-- rollback transaction
-- return -1
-- End
--Else
-- Begin
-- commit transaction
-- return 0
-- End
SELECT Emp_ID,Emp_name from Emp_Master where Dept_id=@deptid

End

END

/*******************************************************************************/

These days, android-based phones are gaining popularity and great apps are available and built every day to enhance its popularity. At this time, I want to work on android development and trying to find out how to communicate android with my existing application. The simplest way to do this is to expose the services to enable communication between android and my existing applications. In this blog post, I am going to look at how android can make use of WCF Services. But before moving forward, I would emphasize that since Android does not provide great support of XML or SOAP-based services, we are going to build WCF Restful Services responsible for providing response in JSON format. So, let’s start by looking first at how we can create WCF services.

I will begin by creating a WCF application named “EmployeeServices “with VS 2010 and deploy it on IIS Server. Although VS2010 provides us with a development server where we can test our services, Android will not be able to communicate withVS2010 Development Server, hence you would be required to deploy your services at IIS and with help from your local system IP address, provide DNS to Android.

Settings -> Wireless Control -> Mobile Networks -> Access Point Names, Select the active and replaced the proxy and port of your DNS

The Employee Entity is mention below

[DataContract]
public class Employee
{
[DataMember]
public int EmployeeId { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string Address { get; set; }
[DataMember]
public string BloodGroup { get; set; }
}

Here is the code of Contract and Services

[ServiceContract(Namespace = "http://services.example.com")]
public interface IEmployeeInfo
{
[OperationContract]
[WebGet(UriTemplate = "GetEmployee/?key={employeeId}" )]
Employee GetEmployee(int employeeId);
}

public class EmployeeInfo : IEmployeeInfo
{
public Employee GetEmployee(int employeeId)
{
Employee employeeInfo = GetEmployees().Where(employee => employee.EmployeeId == employeeId).FirstOrDefault();

return employeeInfo;
}

private List<Employee> GetEmployees()
{
return new List<Employee> {
new Employee { EmployeeId = 11, FirstName = "Patel", LastName = "Viral", Address="A-175 Block 1" , BloodGroup = "B+" },
new Employee { EmployeeId = 22, FirstName = "Patel", LastName = "Sunil", Address="B-176 Block 2" , BloodGroup = "O-" },
new Employee { EmployeeId = 33, FirstName = "Patel", LastName = "Mayur", Address="C-177 Block 3" , BloodGroup = "A+" },
new Employee { EmployeeId = 44, FirstName = "Kundan", LastName = "Kishor", Address="D-178 Block 4" , BloodGroup = "AB+" },
new Employee { EmployeeId = 55, FirstName = "Vijay", LastName = "Rai", Address="E-179 Block 5" , BloodGroup = "B+" },
new Employee { EmployeeId = 66, FirstName = "Fahad", LastName = "Ahmed", Address="F-180 Block 6" , BloodGroup = "B+" },
new Employee { EmployeeId = 77, FirstName = "Mahboob", LastName = "Ikram", Address="G-181 Block 7" , BloodGroup = "B+" },
new Employee { EmployeeId = 88, FirstName = "Saif", LastName = "Ali", Address="H-182 Block 8" , BloodGroup = "O+" },
new Employee { EmployeeId = 99, FirstName = "Nasir", LastName = "Saleem", Address="J-183 Block 9" , BloodGroup = "B+" },
new Employee { EmployeeId = 111, FirstName = "Yasir", LastName = "Shah", Address="I-184 Block 10" , BloodGroup = "O+" },
new Employee { EmployeeId = 222, FirstName = "Saad", LastName = "Usman", Address="J-185 Block 11" , BloodGroup = "B+" },
new Employee { EmployeeId = 333, FirstName = "Yaseen", LastName = "Wahid", Address="K-186 Block 12" , BloodGroup = "B+" },
new Employee { EmployeeId = 444, FirstName = "Qasim", LastName = "Wasi", Address="L-187 Block 13" , BloodGroup = "B+" },
new Employee { EmployeeId = 555, FirstName = "Asad", LastName = "Tamoor", Address="M-188 Block 14" , BloodGroup = "A+" },
new Employee { EmployeeId = 666, FirstName = "Idress", LastName = "Khan", Address="N-189 Block 15" , BloodGroup = "B+" },
new Employee { EmployeeId = 777, FirstName = "Rafa", LastName = "Rauf", Address="O-190 Block 16" , BloodGroup = "B+" },
new Employee { EmployeeId = 888, FirstName = "Fazain", LastName = "Farooq", Address="P-191 Block 17" , BloodGroup = "B+" },
new Employee { EmployeeId = 999, FirstName = "Ali", LastName = "Akber", Address="Q-192 Block 18" , BloodGroup = "B+" },
new Employee { EmployeeId = 1111, FirstName = "Irfan", LastName = "Khan", Address="R-193 Block 19" , BloodGroup = "B+" },
new Employee { EmployeeId = 2222, FirstName = "Omair", LastName = "Ali", Address="S-194 Block 20" , BloodGroup = "B+" },
new Employee { EmployeeId = 3333, FirstName = "Wasi", LastName = "Ahmed", Address="T-195 Block 21" , BloodGroup = "B+" },

};
}
}

Now here is the Code for Web.Config File.

<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint helpEnabled="true"
automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
<services>
<service name="EmployeeService.EmployeeInfo">
<endpoint kind="webHttpEndpoint"
contract="EmployeeService.IEmployeeInfo" />
</service>
</services>
</system.serviceModel>
</configuration>

In the WCF services I created an Employee Entity which has some employee information properties, and wrote a method which provides the collection of dummy data. You can replace it with your desired repository. To keep things simple, I am going to with simple approach. Next I created a contract in services named “GetEmployee” which is responsible to take the EmployeeID (at some places I refer to it as employee code) and if the matching employee exists the system will provide the complete entity of employee otherwise send it to blank. At the contract, annotate the URI Template,and I am creating an automated formatted service, which means that the same services will provide the data in form of XML or JSON based on the header information of the request. For further clarification, you may refer to one of my previous blog post. WCF 4.0 Automatic Formatting with Jquery Ajax.

Now the services are finalized and it’s time to move towards the Android side. For Android development, I have configured the required ADT plug-in, AVDand Android SDK in Eclipse IDE. Now, I am going to create Android Project named “EmployeeInfo” and click on Next button.

At this stage, I will select ‘Android 2.2’(Froyo)because as AVD I have configured Android 2.2

In the image below, you can find other information where Create Activity name is EmployeeInfoActivity.

Here is the code for EmployeeInfoActivity, in which I am using JSON Object to parse the JSON string I received from services. HttpGet has setter method of header, using which we can request the server for JSON data. Retrieve the data from the server and set them with TextView which are already placed at Android UI.

 

public class EmploeeInfoActivity extends Activity {

        private final static String EMPLOYEE_SERVICE_URI = "http://192.168.1.3/EmployeeService/EmployeeInfo.svc/GetEmployee/?key=";

        private EditText evEmployeeId;
private TextView tvEmployeeCode;
private TextView tvName;
private TextView tvAddress;
private TextView tvBloodGroup;
        private Button bSearchEmployee;
        private LinearLayout linearLayoutEmp;
        private LinearLayout linearLayoutError;

        /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

evEmployeeId = (EditText)findViewById(R.id.evEmployeeCode);

tvEmployeeCode = (TextView)findViewById(R.id.tvEmployeeCode);
tvName = (TextView)findViewById(R.id.tvEmployeeName);
tvAddress = (TextView)findViewById(R.id.tvAddress);
tvBloodGroup = (TextView)findViewById(R.id.tvBloodGroup);

linearLayoutEmp = (LinearLayout)findViewById(R.id.lLayoutEmployeeInfo);
linearLayoutError = (LinearLayout)findViewById(R.id.lLayoutError);

linearLayoutEmp.setVisibility(View.GONE);
linearLayoutError.setVisibility(View.GONE);
}

public void onSearchClick(View view)
{
try     {

                DefaultHttpClient client = new DefaultHttpClient();
                // http get request
                HttpGet request = new HttpGet(EMPLOYEE_SERVICE_URI + evEmployeeId.getText());

                // set the hedear to get the data in JSON formate
                request.setHeader("Accept", "application/json");
                request.setHeader("Content-type", "application/json");

                //get the response
                HttpResponse response = client.execute(request);

                HttpEntity entity = response.getEntity();

                //if entity contect lenght 0, means no employee exist in the system with these code
                if(entity.getContentLength() != 0) {
                       // stream reader object
                        Reader employeeReader = new InputStreamReader(response.getEntity().getContent());
                       //create a buffer to fill if from reader
                        char[] buffer = new char[(int) response.getEntity().getContentLength()];
                       //fill the buffer by the help of reader
                       employeeReader.read(buffer);
                       //close the reader streams
                       employeeReader.close();

                       //for the employee json object
                       JSONObject employee =  new JSONObject(new String(buffer));

                       //set the text of text view
                       tvEmployeeCode.setText("Code: " + employee.getString("EmployeeId"));
                        tvName.setText("Name: " + employee.getString("FirstName") + " " + employee.getString("LastName"));
                       tvAddress.setText("Address: " + employee.getString("Address"));
                        tvBloodGroup.setText("Blood Group: " + employee.getString("BloodGroup"));

                       //show hide layout
                       linearLayoutError.setVisibility(View.GONE);
                       linearLayoutEmp.setVisibility(View.VISIBLE);
                }
                else {
                        linearLayoutEmp.setVisibility(View.GONE);
                        linearLayoutError.setVisibility(View.VISIBLE);
                }

}
catch (Exception e) {
//any exception show the error layout
linearLayoutEmp.setVisibility(View.GONE);
linearLayoutError.setVisibility(View.VISIBLE);
e.printStackTrace();
}

}
}

Now I am going to place control at layout.xml file for UI of the android, Search button is bound with onSearchClick event in EmployeeInfoActivity. One EditText, four TextView objects to display the employee information and if the employee information does not exist or garbage input, then it will display an error message.

After that, we have to put the internet permission in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

Now here are the final results:

Now if there is an error, error message(s) will  be displayed:

In this post, I just demonstrated how we can facilitate communication between Android and WCF services, using which we can easily perform all the CURD Operations. I hope you will enjoy the post and give your valuable feedback on it

Happy Coding

Here’s a query to calculate the Age in Years, Months, Days, Hours and Minutes

declare @birth_day datetime
set @birth_day ='19660527 12:34:22'
select
 years,
 months,
 case
 when day(@birth_day)>day(getdate())
 then day(getdate())+
 datediff(day,@birth_day,dateadd(month,datediff(month,0,@birth_day)+1,0))-1
 else day(getdate())-day(@birth_day)
 end as days,
 datepart(hour,convert(varchar(10),dateadd(minute,minutes,0),108)) as hours,
 datepart(minute,convert(varchar(10),dateadd(minute,minutes,0),108)) as minutes
from
(
select
 years,
 datediff(month,dateadd(year,years,@birth_day),getdate())+
 case
 when day(getdate())>=day(@birth_day)
 then 0
 else -1 
 end as months,
 datediff(minute,convert(varchar(8),@birth_day,108),
 convert(varchar(8),getdate(),108)) as minutes
from
(
select
 datediff(year,@birth_day,getdate()) +
 case
 when month(getdate())>=month(@birth_day)
 then 0
 else -1
 end as years
) as t
) as t

In the query shown above, the inner query finds the year difference between current date and birth date. The case expression checks whether current month is greater than the month of birth date. If it is greater, a full year is completed, else the full year is not completed and one year is reduced from the result.

A similar check is done for month too. The outer parts calculate the hours and minutes.

OUTPUT

years           months          days            hours     minutes
44                    4                         5                        0                 0

Hello world!

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

Create your own website, free on WordPress.com.Create your own website.
Start free