Introduction
In this piece of code, I have consumed a WCF service in MVC web application which comprises one view, one controller and one model. Here, view belongs to one action method but invokes other action method as well for different purposes, i.e. insert
and delete
.
Using the Code
- I have taken a blank solution and added 2 different projects in that:
- WCF service library project
- MVC web application using razor engine
- In WCF services, I simply used an interface for service operation and data contracts and two additional files for SQL connection and DML operations.
- In MVC web application, I have used one model which does that part of calling functions from service using proxy class and manipulating them using containers like dataset or lists.
- There is one controller namely
MainController
which has an action method "Index
" that gets the data from SQL table, which has a view attached "Index.cshtml". Controller has 2 more action methods for insertion and delete functionality.
- In view, I have used simple HTML controls and strongly typed controls, and JavaScript function to select multiple checkboxes and redirect to action methods.
(some codes in WCF are unused, one may use them to manipulate further.)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Net.Security;
using System.Data.Objects;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
namespace WcfServiceLibrary1
{
[ServiceContract]
public interface IREGService
{
[OperationContract]
int InsertUser(string name, string password, string country, string email);
[OperationContract]
DataSet GetInfo();
[OperationContract]
int DeleteUser(string ID);
[OperationContract]
DataSet GetCountry();
}
[DataContract]
public class Users
{
private string _UserName;
[DataMember]
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
private string _Password;
[DataMember]
public string Password
{
get { return _Password; }
set { _Password = value; }
}
private string _Country;
[DataMember]
public string Country
{
get { return _Country; }
set { _Country = value; }
}
private string _Email;
[DataMember]
public string Email
{
get { return _Email; }
set { _Email = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
namespace WcfServiceLibrary1
{
public class REGService : IREGService
{
public int InsertUser(string UserName, string Password, string Country, string Email)
{
RegistraionDAO rdoa = new RegistraionDAO();
int Result = 0;
int OUT_ERR_NO;
string OUT_ERR_IDEN;
string OUT_ERR_MSG;
string strparams = string.Format
("Parameters : {0},{1},{2},{3}", UserName, Password, Country, Email);
try
{
Result = rdoa.InsertUser
(UserName, Password, Country,
Email, out OUT_ERR_NO, out OUT_ERR_MSG, out OUT_ERR_IDEN);
} catch
{
Result = -1;
}
finally{
}
return Result;
}
public DataSet GetInfo()
{
DataSet ods = new DataSet();
RegistraionDAO rdoa = new RegistraionDAO();
int Result = -1;
int OUT_ERR_NO;
string OUT_ERR_IDEN;
string OUT_ERR_MSG;
string strparams = string.Format("Parameters : ");
try
{
Result = rdoa.GetUser
(out OUT_ERR_NO, out OUT_ERR_MSG, out OUT_ERR_IDEN, out ods);
}
catch
{
}
finally
{
}
return ods;
}
public DataSet GetCountry()
{
DataSet countrylist = new DataSet();
RegistraionDAO rdoa = new RegistraionDAO();
int Result = -1;
int OUT_ERR_NO;
string OUT_ERR_IDEN;
string OUT_ERR_MSG;
string strparams = string.Format("Parameters : ");
try
{
Result = rdoa.GetCountry
(out OUT_ERR_NO, out OUT_ERR_MSG, out OUT_ERR_IDEN, out countrylist);
}
catch
{
}
finally
{
}
return countrylist;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Collections;
namespace WcfServiceLibrary1
{
class SqlHelper
{
private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
public static int ExecuteNonQuery(string connectionString,
CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection conn = new SqlConnection(connectionString))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
}
public static int ExecuteNonQuery(SqlConnection connection,
CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
public static int ExecuteNonQuery(SqlTransaction trans,
CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
public static SqlDataReader ExecuteReader(string connectionString,
CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
try
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch
{
conn.Close();
throw;
}
}
public static object ExecuteScalar(string connectionString,
CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection connection = new SqlConnection(connectionString))
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
}
public static object ExecuteScalar(SqlConnection connection,
CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
public static void CacheParameters
(string cacheKey, params SqlParameter[] commandParameters)
{
parmCache[cacheKey] = commandParameters;
}
public static SqlParameter[] GetCachedParameters(string cacheKey)
{
SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
if (cachedParms == null)
return null;
SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
for (int i = 0, j = cachedParms.Length; i < j; i++)
clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
return clonedParms;
}
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn,
SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType,
string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
cmd.CommandTimeout = Convert.ToInt32
(ConfigurationManager.AppSettings.Get("COMMAND_TIME_OUT"));
PrepareCommand(cmd, con, null, cmdType, cmdText, commandParameters);
SqlDataAdapter sqlData = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sqlData.Fill(ds);
return ds;
}
}
}
}
-------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Web;
namespace WcfServiceLibrary1
{
class RegistraionDAO
{
private string GetConnectionString()
{
string strconn;
strconn = ConfigurationManager.ConnectionStrings
["SQLConnString"].ConnectionString;
return strconn;
}
public int InsertUser(string username, string password,
string country, string email, out int OUT_ERR_NO,
out string OUT_ERR_MSG,
out string OUT_ERR_IDEN)
{
int result = 0;
string connectionstring = GetConnectionString();
SqlTransaction objtrans = null;
SqlConnection objcon = null;
try
{
objcon = new SqlConnection(connectionstring);
objcon.Open();
objtrans = objcon.BeginTransaction();
SqlParameter[] paramsInfo = new SqlParameter[7];
paramsInfo[0] = new SqlParameter("@IN_USER_NAME", SqlDbType.NVarChar, 100);
paramsInfo[0].Value = username;
paramsInfo[1] = new SqlParameter("@IN_PASSWORD", SqlDbType.NVarChar, 100);
paramsInfo[1].Value = password;
paramsInfo[2] = new SqlParameter("@IN_COUNTRY", SqlDbType.NVarChar, 100);
paramsInfo[2].Value = country;
paramsInfo[3] = new SqlParameter("@IN_EMAIL", SqlDbType.NVarChar, 100);
paramsInfo[3].Value = email;
paramsInfo[4] = new SqlParameter("@OUT_ERR_NO", SqlDbType.Int);
paramsInfo[4].Direction = ParameterDirection.Output;
paramsInfo[5] = new SqlParameter("@OUT_ERR_MSG", SqlDbType.VarChar, 500);
paramsInfo[5].Direction = ParameterDirection.Output;
paramsInfo[6] = new SqlParameter("@OUT_ERR_IDEN", SqlDbType.VarChar, 500);
paramsInfo[6].Direction = ParameterDirection.Output;
SqlHelper.ExecuteNonQuery
(objtrans, CommandType.StoredProcedure, "PKG_INSERT_USER", paramsInfo);
OUT_ERR_NO = Convert.ToInt32(paramsInfo[4].Value.ToString());
OUT_ERR_MSG = paramsInfo[5].Value.ToString();
OUT_ERR_IDEN = paramsInfo[6].Value.ToString();
if (OUT_ERR_NO == 0)
{
objtrans.Commit();
result = 1;
}
else
{
objtrans.Rollback();
result = -1;
}
}
catch (Exception excp)
{
if (objtrans != null)
objtrans.Rollback();
OUT_ERR_NO = -1;
OUT_ERR_MSG = excp.Message.ToString();
OUT_ERR_IDEN = excp.Source.ToString();
}
finally
{
objtrans = null;
if (objcon != null)
{
if (objcon.State == ConnectionState.Open)
objcon.Close();
objcon = null;
}
}
return result;
}
public int GetUser(out int OUT_ERR_NO,
out string OUT_ERR_MSG,
out string OUT_ERR_IDEN,
out DataSet ods)
{
int _intResult = -1;
string connectionString = GetConnectionString();
ods = new DataSet();
try
{
SqlParameter[] paramsInfo = new SqlParameter[3];
paramsInfo[0] = new SqlParameter("@OUT_ERR_NO", SqlDbType.Int);
paramsInfo[0].Direction = ParameterDirection.Output;
paramsInfo[1] = new SqlParameter("@OUT_ERR_MSG", SqlDbType.VarChar, 500);
paramsInfo[1].Direction = ParameterDirection.Output;
paramsInfo[2] = new SqlParameter("@OUT_ERR_IDEN", SqlDbType.VarChar, 500);
paramsInfo[2].Direction = ParameterDirection.Output;
ods = SqlHelper.ExecuteDataSet(connectionString, CommandType.StoredProcedure,
"PKG_GET_USER", paramsInfo);
OUT_ERR_NO = Convert.ToInt32(paramsInfo[0].Value.ToString());
OUT_ERR_MSG = paramsInfo[1].Value.ToString();
OUT_ERR_IDEN = paramsInfo[2].Value.ToString();
_intResult = 0;
}
catch (Exception excp)
{
OUT_ERR_NO = -1;
OUT_ERR_MSG = excp.Message.ToString();
OUT_ERR_IDEN = excp.Source.ToString();
}
finally
{
}
return _intResult;
}
public int DeleteUser(string id, out int OUT_ERR_NO,
out string OUT_ERR_MSG,
out string OUT_ERR_IDEN)
{
int _intResult = -1;
string connectionString = GetConnectionString();
try
{
SqlParameter[] paramsInfo = new SqlParameter[4];
paramsInfo[0] = new SqlParameter("@IN_ID", SqlDbType.VarChar);
paramsInfo[0].Value = id;
paramsInfo[1] = new SqlParameter("@OUT_ERR_NO", SqlDbType.Int);
paramsInfo[1].Direction = ParameterDirection.Output;
paramsInfo[2] = new SqlParameter("@OUT_ERR_MSG", SqlDbType.VarChar, 500);
paramsInfo[2].Direction = ParameterDirection.Output;
paramsInfo[3] = new SqlParameter("@OUT_ERR_IDEN", SqlDbType.VarChar, 500);
paramsInfo[3].Direction = ParameterDirection.Output;
SqlHelper.ExecuteDataSet(connectionString, CommandType.StoredProcedure,
"PKG_DELETE_USER", paramsInfo);
OUT_ERR_NO = Convert.ToInt32(paramsInfo[0].Value.ToString());
OUT_ERR_MSG = paramsInfo[1].Value.ToString();
OUT_ERR_IDEN = paramsInfo[2].Value.ToString();
_intResult = 0;
}
catch (Exception excp)
{
OUT_ERR_NO = -1;
OUT_ERR_MSG = excp.Message.ToString();
OUT_ERR_IDEN = excp.Source.ToString();
}
finally
{
}
return _intResult;
}
public int GetCountry(out int OUT_ERR_NO,
out string OUT_ERR_MSG,
out string OUT_ERR_IDEN,
out DataSet Countrylist)
{
int _intResult = -1;
string connectionString = GetConnectionString();
Countrylist = new DataSet();
try
{
SqlParameter[] paramsInfo = new SqlParameter[3];
paramsInfo[0] = new SqlParameter("@OUT_ERR_NO", SqlDbType.Int);
paramsInfo[0].Direction = ParameterDirection.Output;
paramsInfo[1] = new SqlParameter("@OUT_ERR_MSG", SqlDbType.VarChar, 500);
paramsInfo[1].Direction = ParameterDirection.Output;
paramsInfo[2] = new SqlParameter("@OUT_ERR_IDEN", SqlDbType.VarChar, 500);
paramsInfo[2].Direction = ParameterDirection.Output;
Countrylist = SqlHelper.ExecuteDataSet(connectionString, CommandType.StoredProcedure,
"PKG_GET_COUNTRY", paramsInfo);
OUT_ERR_NO = Convert.ToInt32(paramsInfo[0].Value.ToString());
OUT_ERR_MSG = paramsInfo[1].Value.ToString();
OUT_ERR_IDEN = paramsInfo[2].Value.ToString();
_intResult = 0;
}
catch (Exception excp)
{
OUT_ERR_NO = -1;
OUT_ERR_MSG = excp.Message.ToString();
OUT_ERR_IDEN = excp.Source.ToString();
}
finally
{
}
return _intResult;
}
}
}
------------------------------Now add MVC project to the solution--------------------------------
MVC Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.ComponentModel.DataAnnotations;
using proxy = MvcRegApp.ServRef.REGServiceClient;
using System.Web.Mvc;
public class UserModel
{
proxy Objserv = new proxy();
private string _UserName;
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
private string _Password;
public string Password
{
get { return _Password; }
set { _Password = value; }
}
private string _Country;
public string Country
{
get { return _Country; }
set { _Country = value; }
}
private string _Email;
public string Email
{
get { return _Email; }
set { _Email = value; }
}
public DataSet ODS = new DataSet();
public DataSet CpuntrySet = new DataSet();
public List<SelectListItem> SelectCountrylist = new List<SelectListItem>();
public void InsertData(UserModel objmodel)
{
Objserv.InsertUser(objmodel._UserName,
objmodel._Password, objmodel._Country, objmodel._Email);
}
public void GetData()
{
ODS = Objserv.GetInfo();
}
public void GetCountry()
{
CpuntrySet = Objserv.GetCountry();
foreach (DataRow dr in CpuntrySet.Tables[0].Rows)
{
SelectCountrylist.Add(new SelectListItem
{ Text = dr["NAME"].ToString(),
Value = dr["NAME"].ToString() });
}
}
public void DeleteData(string id)
{
Objserv.DeleteUser(id);
}
}
public class MainController : Controller
{
UserModel ObjModel = new UserModel();
public ActionResult Index()
{
ObjModel.GetCountry();
ObjModel.GetData();
return View(ObjModel);
}
public ActionResult InsertUser(UserModel UMDL)
{
UMDL.InsertData(UMDL);
return RedirectToAction("Index");
}
public ActionResult DeleteUser(string id)
{
ObjModel.DeleteData(id);
return RedirectToAction("Index");
}
}
@model MvcRegApp.Models.UserModel
@using System.Data;
@{
ViewBag.Title = "Index";
}
<h2 align="center">Registration Form</h2>
@*SELECT ALL SCRIPT- to check all the check boxes in table in one go*@
<script type="text/javascript">
function toggle(source) {
checkboxes = document.getElementsByName('SELECTALL');
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<script src="~/Scripts/jquery-2.1.1.js"
type="text/javascript"></script>
<script src="~/Scripts/jquery.tablesorter.js"
type="text/javascript"></script>
<script src="~/Scripts/jquery.tablesorter.pager.js"
type="text/javascript"></script>
@* PAGING SCRIPT-- to break the table into fixed length page*@
<script type="text/javascript">
$(document).ready(function () {
$("#dt_basic")
.tablesorter({ widthFixed: true, widgets: ['zebra'] })
.tablesorterPager({ container: $("#pager") });
});
</script>
@*Redirect To Delete-- script passing ids to the delete method in controller*@
<script type="text/javascript">
function getval(source) {
var id = "";
checkboxes = document.getElementsByName('SELECTALL');
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked) {
id += "," + checkboxes[i].value;
}
}
window.location = "Main/DeleteUser/" + id;
}
</script>
@* styling for the table *@
<style type="text/css">
table {
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
}
th
{
background-color:#C1D6DE;
}
td
{
width:auto;
background-color:#FFE9D4;
}
.text
{
background-color:transparent;
border-style:none;
}
#un
{
background-color:transparent;
border:none;
color:Black;
}
</style>
@* thml form containing the strongly typed html controls *@
@using (Html.BeginForm("InsertUser", "Main"))
{
<table align="center">
<tr><td>User Name</td><td>
@Html.TextBoxFor(x => x.UserName)</td></tr>
<tr><td>Password</td><td>
@Html.TextBoxFor(x => x.Password)</td></tr>
<tr><td>Country </td><td>@Html.DropDownListFor
(x => x.Country, Model.SelectCountrylist,
"--Select Country--")</td></tr>
<tr><td>Email </td><td>
@Html.TextBoxFor(x => x.Email)</td></tr>
<tr><td></td><td><input type="submit"
value="Save" /> <button id="cancel"
value="Cancel" type="reset"
style="width:60px">Cancel</button></td></tr>
</table>
}
<div align="center" id="pager"
class="pager" style="text-align: center;">
<img src="../../Images/first.png"
class="first" alt="" />
<img src="../../Images/prev.png"
class="prev" alt=""/>
<span class="pagedisplay"></span>
-->
<img src="../../Images/next.png"
class="next" alt=""/>
<img src="../../Images/last.png"
class="last" alt=""/>
<select class="pagesize">
<option selected="selected" value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
</select>
</div>
<table align="center" id="dt_basic">
<thead>
<tr>
<th>NAME</th><th>PASSWORD</th>
<th>COUNTRY</th><th>EMAIL</th>
<th><input type="checkbox" name="SELECTALL"
value="" onclick="toggle(this)" /></th></tr>
</thead>
<tbody>
@foreach (DataRow dr in Model.ODS.Tables[0].Rows)
{
<tr>
<td>@dr["USERNAME"].ToString()</td>
<td>@dr["PASSWORD"].ToString()</td>
<td>@dr["COUNTRY"].ToString()</td>
<td>@dr["EMAIL"].ToString()</td>
<td><input type="checkbox" name="SELECTALL"
value="@dr["ID"]" /></td>
</tr>
}
</tbody>
</table>
<table align="center">
<tr><td><input type="button" id="delete"
value="Delete" name="Delete"
onclick="getval()"/></td></tr>
</table>
Points of Interest
Insert
, delete
and select
in MVC using WCF WER services