Previously i show you Arcitecture. this is
Coding Guidelines
Reference link is for Arcitecture.
(http://satyabratabehera.blogspot.in/2017/01/web-api-arcitecture-with.html)
Reference link is for Arcitecture.
(http://satyabratabehera.blogspot.in/2017/01/web-api-arcitecture-with.html)
For Example, I have assign a page
which name is Designation.
Before Doing this Page there are 3 steps we are doing. And there are certain rules you should obey. That are explain below-:
Before Doing this Page there are 3 steps we are doing. And there are certain rules you should obey. That are explain below-:
Rule001
|
Your interface name is must be ITestDesignationService. As your table name TestDesignation. Ex.(“ I” + “ Table Name” + “Service”)
|
Rule002
|
Your Class name is must be TestDesignationService. As your table name TestDesignation. Ex.(“ Table Name” + “Service”)
|
Rule003
|
Your Repository Private Instance Name must be testDesignationRepository. As your table name TestDesignation.
|
Rule004
|
Public Repository Creation Properties Name must be TestDesignationRepository. As your table name TestDesignation.
|
Rule005
|
Region Should be maintained.
|
Rule006
|
Always use Web Api in your Web Application.
|
Rule007
|
Naming Convention should be maintained for User defined
functions.
|
Rule008
|
Use appropriate prefix for the UI elements so that you
can identify them from the rest of the variables. Like. Label:
lbl, TextBox: txt, Gridview: gv, Button: btn; ImageButton:
ibtn,LinkButton: lbtn, DropDownList: ddl, ListBox: lb, DataList:
dl, Panel: pnl, PlaceHolder: phd, Table: tbl, Validators:
val. …etc…
|
1. First Point
è Go to Unit of Work from Data Model. Create a Repository
Private instance in Private
Member Variable Area. That code Look like this.
#region Private member variables...
private AdminEntitiesModel _context = null; // Already There.
Step 1:
private GenericRepository<TestDesignation>
_testDesignationRepository; // to Add
#endregion.
è Next in same page set property for Designation
repository.
#region Public Repository Creation properties...
Step 2:
public GenericRepository<TestDesignation> TestDesignationRepository
{
get
{
if (this._testDesignationRepository
== null)
this._testDesignationRepository =
new GenericRepository<TestDesignation>(_context);
return _testDesignationRepository;
}
}
#endregion
2. Second Point
è Go to Business Services. First Create an Interface which
name is ITestDesignationService.
Write Some
Method Which you need. And one thing method name Should be look like this. Your
Table Name Use. PFB the example.
namespace BusinessServices
{
public interface ITestDesignationService
{
IEnumerable<TestDesignation> GetAllTestDesignation();
TestDepartment GetAllTestDesignationById(int DesignationId);
TestDepartment InsertTestDesignation(TestDepartment TestDesignationEntity);
TestDepartment UpdateTestDesignation(int EmployeeId, TestDepartment TestDesignationEntity);
bool DeleteTestDesignation(int DesignationId);
}}
è
Next create a
class which inherits from ITestDesignationService Interface.
One thing after adding a
class you declare an instance for UnitOfWork Class as readonly. And in constructor call the default
constructor using that reference. PFB the example.
public class TestDesignationService : ITestDesignationService
{
private readonly UnitOfWork _unitOfWork;
/// <summary>
/// Public constructor.
/// </summary>
public TestDesignationService()
{
_unitOfWork = new UnitOfWork();
}
/// <summary>
/// Fetches all the Designation.
/// </summary>
/// <returns></returns>
public IEnumerable<TestDesignation> GetAllTestDesignation()
{
var lstdesignation =
_unitOfWork.TestDesignationRepository.GetAll();
if (lstdesignation.Any())
{
return lstdesignation;
}
return null;
}
/// <summary>
/// Fetches Designation By Id.
/// </summary>
/// <returns></returns>
public TestDesignation GetAllTestDesignationById(int DesignationId)
{
var testdesignation =
_unitOfWork.TestDesignationRepository.GetByID(DesignationId);
if (testdesignation != null)
{
return testdesignation;
}
return null;
}
/// <summary>
/// TestDesignation
/// </summary>
/// <param name="TestDesignationEntity"></param>
/// <returns></returns>
public TestDesignation InsertTestDesignation(TestDesignation TestDesignationEntity)
{
using (var scope = new TransactionScope())
{
var testdesignation = new TestDesignation
{
DesignationId =
TestDesignationEntity.DesignationId,
DesignationName =
TestDesignationEntity.DesignationName,
DesignationCode =
TestDesignationEntity.DesignationCode
};
_unitOfWork.TestDesignationRepository.Insert(testdesignation);
_unitOfWork.Save();
scope.Complete();
return testdesignation;
}
}
/// <summary>
/// Updates a TestDesignation
/// </summary>
/// <param
name="TestDesignationId"></param>
/// <param
name="TestDesignationEntity"></param>
/// <returns></returns>
public TestDesignation UpdateTestDesignation(int Designationid, TestDesignation TestDesignationEntity)
{
TestDesignation testdesignation = null;
if (TestDesignationEntity != null)
{
using (var scope = new TransactionScope())
{
testdesignation =
_unitOfWork.TestDesignationRepository.GetByID(Designationid);
if (testdesignation != null)
{
testdesignation.DesignationId
= TestDesignationEntity.DesignationId;
testdesignation.DesignationName = TestDesignationEntity.DesignationName;
testdesignation.DesignationCode = TestDesignationEntity.DesignationCode;
_unitOfWork.TestDesignationRepository.Update(testdesignation);
_unitOfWork.Save();
scope.Complete();
}
}
}
return testdesignation;
}
/// <summary>
/// Deletes a particular
TestDesignation
/// </summary>
/// <param
name="TestDesignationId"></param>
/// <returns></returns>
public bool DeleteTestDesignation(int DesignationId)
{
var success = false;
if (DesignationId >= 0)
{
using (var scope = new TransactionScope())
{
var testdesigantion =
_unitOfWork.TestDesignationRepository.GetByID(DesignationId);
if (testdesigantion != null)
{
_unitOfWork.TestDesignationRepository.Delete(testdesigantion);
_unitOfWork.Save();
scope.Complete();
success = true;
}
}
}
return success;
}
}
3. Third Point
è Go to
Web API Services. Add a read/write Controller which name is TestDesignationController.
namespace KenAdmin.Controllers
{
public class TestDesignationController : ApiController
{
private readonly ITestDesignationService _testDesignationService;
public TestDesignationController()
{
_testDesignationService = new TestDesignationService();
}
/// <summary>
/// Get All Designation
/// </summary>
/// <remarks>
/// Gets the List of Designation
/// </remarks>
/// <returns></returns>
/// <response
code="200"></response>
// GET:
api/TestDesignation
public HttpResponseMessage Get()
{
var lstdesignation =
_testDesignationService.GetAllTestDesignation();
if (lstdesignation != null)
{
var lstdata = lstdesignation as List<TestDesignation> ?? lstdesignation.ToList();
if (lstdata.Any())
return
Request.CreateResponse(HttpStatusCode.OK, lstdata);
}
return Request.CreateErrorResponse(HttpStatusCode.NotFound,
"Designation not found");
}
/// <summary>
/// Get All Designation By Id
/// </summary>
/// <remarks>
/// Gets the List of Designation By Id
/// </remarks>
/// <returns></returns>
/// <response
code="200"></response>
// GET:
api/TestDesignation/5
public HttpResponseMessage Get(int id)
{
try
{
var Temp =
_testDesignationService.GetAllTestDesignationById(id);
if (Temp != null)
return
Request.CreateResponse(HttpStatusCode.OK, Temp);
return Request.CreateErrorResponse(HttpStatusCode.NotFound,
"No Test Employee found for this
id");
}
catch (Exception)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
/// <summary>
/// Insert Designation
/// </summary>
/// <remarks>
/// Insert the List of Designation
/// </remarks>
/// <returns></returns>
/// <response
code="200"></response>
// POST:
api/TestDesignation
public HttpResponseMessage Post([FromBody]TestDesignation obj)
{
try
{
var res = _testDesignationService.InsertTestDesignation(obj);
if (res != null)
return Request.CreateResponse(HttpStatusCode.OK,
res);
else
return
Request.CreateErrorResponse(HttpStatusCode.NotFound, "Data Not
Saved");
}
catch (Exception)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
/// <summary>
/// Update Designation
/// </summary>
/// <remarks>
/// Update the Designation By Id
/// </remarks>
/// <returns></returns>
/// <response
code="200"></response>
// PUT:
api/TestDesignation/5
public HttpResponseMessage Put(int id, [FromBody]TestDesignation obj)
{
try
{
TestDesignation res = null;
if (id >= 0)
{
res =
_testDesignationService.UpdateTestDesignation(id, obj);
}
if (res != null)
return
Request.CreateResponse(HttpStatusCode.OK, res);
else
return
Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Data
Not Updated");
}
catch (Exception)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
/// <summary>
/// Delete Designation
/// </summary>
/// <Delete>
/// Update the Designation By Id
/// </remarks>
/// <returns></returns>
/// <response
code="200"></response>
//
DELETE: api/TestDesignation/5
public HttpResponseMessage Delete(int id)
{
bool res = false;
if (id >= 0)
res =
_testDesignationService.DeleteTestDesignation(id);
if (!res)
return Request.CreateResponse(HttpStatusCode.OK, res);
else
return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable,
"Cant Be Deleted Reference
Exist");
}
}
}
=======================================Verified--========================================
è When you go to design your page in Web App, It must be mandatory
to use telerik control.
è Try to avoid inline Stylesheet.
Now I create a
design for Designation Page. Just short example of Source Code Design.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="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>
<style type="text/css">
.rgCommandCell {
background-color: #7dd3f7 !important;
}
.RadGrid_Outlook .rgHeader, .RadGrid_Outlook th.rgResizeCol, .RadGrid_Outlook .rgHeaderWrapper {
background: #7dd3f7 !important;
}
.RadGrid_Outlook .rgMasterTable .rgSelectedCell, .RadGrid_Outlook .rgSelectedRow {
background: #7dd3f7 !important;
}
.bdradius {
height: 518px !important;
}
.RadGrid_Outlook {
border: 1px solid #00D3FF !important;
}
#application {
background-color: #FCB040 !important;
}
</style>
<telerik:RadStyleSheetManager ID="RadStyleSheetManager1" runat="server" />
</head>
<body>
<form id="form1" runat="server">
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
<asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
<asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
</Scripts>
</telerik:RadScriptManager>
<script type="text/javascript">
//Put
your JavaScript code here.
</script>
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
</telerik:RadAjaxManager>
<div style="margin-left: 300px; margin-right: 300px; margin-top: 20px;">
<div style="width: 100%; float: left; margin-bottom:
2%;">
<div style="width: 40%; float: left;">
<telerik:RadLabel ID="lbldesignationcode" runat="server" Text="Designation Code
:"></telerik:RadLabel>
</div>
<div style="width: 58%; float: left;">
<telerik:RadTextBox ID="txtdesignationcode" runat="server"></telerik:RadTextBox>
</div>
</div>
<div style="width: 100%; margin-bottom:
2%;">
<div style="width: 40%; float: left;">
<telerik:RadLabel ID="lbldesignationname" runat="server" Text="Designation Code
:"></telerik:RadLabel>
</div>
<div style="width: 58%; float: left;">
<telerik:RadTextBox ID="txtdesignationName" runat="server"></telerik:RadTextBox>
</div>
</div>
<div style="width: 100%; float: left; margin-bottom: 2%;margin-top:2%;">
<div style="width: 20%;float:left;">
<telerik:RadLabel ID="lblInfomation" runat="server" Text="Designation Code :"></telerik:RadLabel>
</div>
<div style="width: 20%;float:left;">
<telerik:RadButton ID="Radbtn_save" runat="server" Text="Save" OnClick="Radbtn_save_Click"></telerik:RadButton>
</div>
<div style="width: 20%;float:left;">
<telerik:RadButton ID="Radbtn_Update" runat="server" Text="Update" OnClick="Radbtn_Update_Click"></telerik:RadButton>
</div>
<div style="width: 20%;float:left;">
<telerik:RadButton ID="Radbtn_Delete" runat="server" Text="Delete" OnClick="Radbtn_Delete_Click"></telerik:RadButton>
</div>
<div style="width: 20%;float:left;">
</div>
</div>
<div style="width: 100%; float: left; margin-bottom: 2%; margin-left: 10px;">
<telerik:RadGrid ID="Rgv_Designation" AlternatingItemStyle-BackColor="#e0f8f7" CellSpacing="0" PagerStyle-AlwaysVisible="true"
GridLines="Vertical" runat="server" AllowPaging="true" HeaderStyle-Font-Bold="true" Skin="Outlook" PageSize="8" AutoGenerateColumns="false"
AllowSorting="true" AllowFilteringByColumn="true" ShowGroupPanel="True" HeaderStyle-Width="50px" GroupPanel-ForeColor="red"
OnPageIndexChanged="Rgv_Designation_PageIndexChanged" OnPageSizeChanged="Rgv_Designation_PageSizeChanged" OnNeedDataSource="Rgv_Designation_NeedDataSource"
OnItemCommand="Rgv_Designation_ItemCommand" GroupPanelPosition="Top">
<ClientSettings Selecting-AllowRowSelect="true" EnablePostBackOnRowClick="true" ReorderColumnsOnClient="True" AllowDragToGroup="True" AllowColumnsReorder="True">
<Selecting AllowRowSelect="True" EnableDragToSelectRows="False" />
<Resizing AllowRowResize="false" AllowColumnResize="True" EnableRealTimeResize="True" ResizeGridOnColumnResize="False"></Resizing>
<Scrolling AllowScroll="true" SaveScrollPosition="true" UseStaticHeaders="True" FrozenColumnsCount="1" />
</ClientSettings>
<GroupingSettings CaseSensitive="false" ShowUnGroupButton="true" />
<MasterTableView DataKeyNames="DesignationId" AllowMultiColumnSorting="true" CommandItemDisplay="Top" ShowHeadersWhenNoRecords="true" AutoGenerateColumns="false" TableLayout="Fixed" GridLines="None">
<Columns>
<telerik:GridClientSelectColumn UniqueName="ClientSelectColumn" HeaderStyle-Width="3%">
</telerik:GridClientSelectColumn>
<telerik:GridTemplateColumn Visible="false" AllowFiltering="false">
<ItemTemplate>
<%# Container.DataSetIndex+1 %>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="" Visible="false">
<ItemTemplate>
<asp:Label ID="lblDesignationId" runat="server" Text='<%# Eval("DesignationId") %>' Visible="false"></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="DesignationCode" ShowFilterIcon="true" AllowFiltering="true"
HeaderStyle-Width="15%" UniqueName="DesignationCode" SortExpression="DesignationCode" DataField="DesignationCode"
FilterControlWidth="90px" AutoPostBackOnFilter="true" CurrentFilterFunction="Contains"
Groupable="true" GroupByExpression="DesignationCode Group By DesignationCode">
<ItemTemplate>
<asp:Label ID="lblDesignationCode" runat="server" Text='<%# Eval("DesignationCode") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Designation Name" ShowFilterIcon="true"
AllowFiltering="true" DataField="DesignationName"
AutoPostBackOnFilter="true" HeaderStyle-Width="15%" Groupable="true"
GroupByExpression="DesignationName
Group By DesignationName">
<ItemTemplate>
<asp:Label ID="lblDesignationName" runat="server" Text='<%# Eval("DesignationName") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</div>
</div>
</form>
</body>
</html>
Before working on webapp you add a dll for ReadAsAsync. Its Dll
Path is
// Install-Package Microsoft.AspNet.WebApi.Client // Add This dll for ReadAsAsync
Now I go to C# Code Design, That Code Look like this.
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
using BusinessEntities;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Linq;
public partial class Default : System.Web.UI.Page
{
#region Varibale and instance and object Declare Section.
List<TestDesignation>
designationList = null;//Declare Reference.
TestDesignation cityEntity = new TestDesignation(); //Declare Object.
HttpClient client = new HttpClient();
#endregion
#region Methods
private void FillAllDesignation()
{
HttpResponseMessage desi = client.GetAsync("api/TestDesignation").Result;
if (desi.IsSuccessStatusCode)
{
designationList =
desi.Content.ReadAsAsync<List<TestDesignation>>().Result;
var data = (from c in designationList
select new
{
DesignationId =
c.DesignationId,
DesignationCode =
c.DesignationCode,
DesignationName =
c.DesignationName,
}).ToList();
var check = from c in data select c;
if (Convert.ToInt32(check.Count()) > 0)
{
Rgv_Designation.DataSource =
check.ToList();
Rgv_Designation.DataBind();
}
}
}
void Reset()
{
txtdesignationName.Text = "";
txtdesignationcode.Text = "";
}
#endregion
#region Page Load
protected void Page_Load(object sender, EventArgs e)
{
var appsurl = ConfigurationManager.AppSettings["APIPath"].ToString();
client.BaseAddress = new Uri(appsurl);
if (!IsPostBack)
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
FillAllDesignation();
lblInfomation.Text = "Get All Records";
}
}
#endregion
#region
Button Save
protected void Radbtn_save_Click(object sender, EventArgs e)
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
cityEntity.DesignationName = txtdesignationName.Text;
cityEntity.DesignationCode =
txtdesignationcode.Text;
var response = client.PostAsJsonAsync("api/TestDesignation", cityEntity).Result;
if (response.IsSuccessStatusCode)
{
lblInfomation.Text = "Designation Added";
FillAllDesignation();
Reset();
}
else
{
lblInfomation.Text = "Error Code" +
response.StatusCode + " : Message - " + response.ReasonPhrase;
}
}
#endregion
protected void Radbtn_Update_Click(object sender, EventArgs e)
{
if(Session["ApplicationId"]!=null)
{
int id = Convert.ToInt32(Session["ApplicationId"].ToString());
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
cityEntity.DesignationId =id;
cityEntity.DesignationName =
txtdesignationName.Text;
cityEntity.DesignationCode =
txtdesignationcode.Text;
var response = client.PutAsJsonAsync("api/TestDesignation/" + cityEntity.DesignationId, cityEntity).Result;
if (response.IsSuccessStatusCode)
{
lblInfomation.Text = "Designation Updated";
FillAllDesignation();
Reset();
}
else
{
lblInfomation.Text = "Error Code" +
response.StatusCode + " : Message - " + response.ReasonPhrase;
}
}
}
protected void Radbtn_Delete_Click(object sender, EventArgs e)
{
if (Session["ApplicationId"] != null)
{
int id = Convert.ToInt32(Session["ApplicationId"].ToString());
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
cityEntity.DesignationId = id;
var response = client.DeleteAsync("api/TestDesignation/" + cityEntity.DesignationId).Result;
if (response.IsSuccessStatusCode)
{
lblInfomation.Text = "Designation Deleted";
FillAllDesignation();
Reset();
}
else
{
lblInfomation.Text = "Error Code" +
response.StatusCode + " : Message - " + response.ReasonPhrase;
}
}
}
protected void Rgv_Designation_PageIndexChanged(object sender, GridPageChangedEventArgs
e)
{
try
{
int index = e.NewPageIndex;
int current = Rgv_Designation.CurrentPageIndex;
FillAllDesignation();
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
protected void Rgv_Designation_PageSizeChanged(object sender, GridPageSizeChangedEventArgs
e)
{
try
{
int x = Rgv_Designation.PageSize;
Rgv_Designation.PageSize = x;
FillAllDesignation();
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
protected void Rgv_Designation_NeedDataSource(object sender, GridNeedDataSourceEventArgs
e)
{
try
{
HttpResponseMessage desi = client.GetAsync("api/TestDesignation").Result;
if (desi.IsSuccessStatusCode)
{
var designationList = desi.Content.ReadAsAsync<List<TestDesignation>>().Result;
var data = (from m in
designationList.OrderByDescending(x => x.DesignationId).ToList() select m).ToList();
Rgv_Designation.DataSource =
data;
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
protected void Rgv_Designation_ItemCommand(object sender, GridCommandEventArgs e)
{
try
{
#region Goto EditPage
if (e.CommandName == "RowClick")
{
Label lblAppId = (Label)((GridDataItem)(e.Item)).FindControl("lblDesignationId");
int ID = Convert.ToInt32(lblAppId.Text);
Session["ApplicationId"] = lblAppId.Text.Trim();
HttpResponseMessage desi = client.GetAsync("api/TestDesignation").Result;
if (desi.IsSuccessStatusCode)
{
designationList = desi.Content.ReadAsAsync<List<TestDesignation>>().Result;
var data = (from c in designationList
where c.DesignationId == ID
select new
{
DesignationId =
c.DesignationId,
DesignationCode = c.DesignationCode,
DesignationName = c.DesignationName,
}).ToList();
var check = from c in data select c;
if (Convert.ToInt32(check.Count())
> 0)
{
txtdesignationName.Text
= data.ToList()[0].DesignationName;
txtdesignationcode.Text
= data.ToList()[0].DesignationCode;
}
}
}
if (e.CommandName == RadGrid.FilterCommandName)
{
FillAllDesignation();
}
#endregion
}
catch (Exception ex)
{
ex.Message.ToString();
}
}