--------------------------------------------
PendotaAPI - Controller - CustomerController.cs
--------------------------------------------
using PendotaAPI_Repository.DTO;
using PendotaAPI_Repository.Service;
using PendotaAPI_Repository.ServiceContract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace PendotaAPI.Controllers
{
public class CustomerController : ApiController
{
private ICustomer_Repository _ICustomer_Repository;
public CustomerController()
{
this._ICustomer_Repository = new Customer_Repository();
}
[HttpGet]
[Route("api/Customer")]
//GET: api/Customer
public HttpResponseMessage Get()
{
try
{
List<Customer> curList = new List<Customer>();
curList = _ICustomer_Repository.Get();
HttpResponseMessage rea = Request.CreateResponse(HttpStatusCode.OK, curList.ToList());
return rea;
// return Ok(curList.AsEnumerable());
}
catch (Exception ex)
{
return null;
}
}
[Route("api/Customer/{id}")]
// GET: api/Customer/5
[HttpGet]
public Customer Get(int id)
{
return _ICustomer_Repository.GetCustomerById(id);
}
// POST: api/Customer
[HttpPost]
[Route("api/Customer")]
public void Post([FromBody]Customer objCustomer)
{
try
{
_ICustomer_Repository.Save(objCustomer);
}
catch (Exception ex)
{
throw;
}
}
// PUT: api/Customer/5
[HttpPut]
[Route("api/Customer/{id}")]
public void Put(int id, [FromBody]Customer objCustomer)
{
try
{
objCustomer.CustomerID = id;
_ICustomer_Repository.Save(objCustomer);
}
catch (Exception ex)
{
throw;
}
}
// DELETE: api/Customer/5
[HttpDelete]
[Route("api/Customer/{id}")]
public void Delete(int id)
{
try
{
_ICustomer_Repository.Delete(id);
}
catch (Exception ex)
{
throw;
}
}
}
}
--------------------------------------------
PendotaAPI - Web.config
--------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=301879
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6" />
<httpRuntime targetFramework="4.6" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<connectionStrings>
<add name="Dalc_Conn" connectionString="Data Source=DESKTOP-QANVEDT\SQLEXPRESS;Initial Catalog=PendotaDB;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
</customHeaders>
</httpProtocol>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers></system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
--------------------------------------------
PendotaAPI_Repository - DTO - Customer.cs
--------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PendotaAPI_Repository.DTO
{
public class Customer
{
[Key]
public int CustomerID { get; set; }
[Required(ErrorMessage = "Customer Name Required.")]
public string CustomerName { get; set; }
[Required(ErrorMessage = "Customer Phone Required.")]
public string CustomerPhone { get; set; }
[Required(ErrorMessage = "Customer Email Required.")]
public string CustomerEmail { get; set; }
[Required(ErrorMessage = "Country Required.")]
public int Country { get; set; }
public string Address { get; set; }
public string Zipcode { get; set; }
public bool Status { get; set; }
public string CityName { get; set; }
}
}
--------------------------------------------
PendotaAPI_Repository - Service- Customer_Repository.cs
--------------------------------------------
using PendotaAPI_Repository.DataServices;
using PendotaAPI_Repository.ServiceContract;
using PendotaAPI_Repository.DTO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace PendotaAPI_Repository.Service
{
public class Customer_Repository : ICustomer_Repository
{
// Get Customer List
public List<Customer> Get()
{
try
{
SqlParameter[] para = new SqlParameter[0];
return new dalc().FetchListBySP<Customer>("Usp_FetchCustomerList", para);
}
catch (Exception ex)
{
throw;
}
}
// Get Customer
public Customer GetCustomerById(int id)
{
try
{
SqlParameter[] para = new SqlParameter[1];
para[0] = new SqlParameter().CreateParameter("@CustomerID", id);
return new dalc().FetchListBySP<Customer>("Usp_FetchCustomer", para).FirstOrDefault();
}
catch (Exception ex)
{
throw;
}
}
// Get Customer Save
public void Save(Customer objCustomer)
{
try
{
SqlParameter[] para = new SqlParameter[7];
para[0] = new SqlParameter().CreateParameter("@CustomerID", objCustomer.CustomerID);
para[1] = new SqlParameter().CreateParameter("@CustomerName", objCustomer.CustomerName);
para[2] = new SqlParameter().CreateParameter("@CustomerPhone", objCustomer.CustomerPhone);
para[3] = new SqlParameter().CreateParameter("@CustomerEmail", objCustomer.CustomerEmail);
para[4] = new SqlParameter().CreateParameter("@Country", objCustomer.Country);
para[5] = new SqlParameter().CreateParameter("@Address", objCustomer.Address);
para[6] = new SqlParameter().CreateParameter("@Zipcode", objCustomer.Zipcode);
new dalc().IUDbySP("Usp_SaveCustomer", para);
}
catch (Exception ex)
{
throw;
}
}
// Get Customer Delete
public void Delete(int id)
{
try
{
SqlParameter[] para = new SqlParameter[1];
para[0] = new SqlParameter().CreateParameter("@CustomerID", id);
new dalc().IUDbySP("Usp_DeleteCustomer", para);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
--------------------------------------------
PendotaAPI_Repository - ServiceContract - ICustomer_Repository.cs
--------------------------------------------
using PendotaAPI_Repository.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PendotaAPI_Repository.ServiceContract
{
public interface ICustomer_Repository
{
List<Customer> Get();
Customer GetCustomerById(int id);
void Save(Customer objBank);
void Delete(int id);
}
}
--------------------------------------------
PendotaAPI_Repository - DataServices - dalc.cs
--------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Configuration;
namespace PendotaAPI_Repository.DataServices
{
public class dalc
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Dalc_Conn"].ConnectionString);
public dalc()
{
}
// CRUD Opration By String Query
public void IUDByQuery(string str)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = str;
//cmd.Parameters.AddRange(para);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Dispose();
}
}
// Fetch DataTable By String Query
public DataTable FetchDataTableByQuery(string str)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = str.ToString();
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
conn.Open();
da.Fill(dt);
return dt;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
// conn.Dispose();
}
}
// Fetch DataSet By String Query
public DataSet FetchDataSetByQuery(string str)
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandText = str.ToString();
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
conn.Open();
da.Fill(ds);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
conn.Dispose();
}
}
// Fetch List By String Query
public List<T> FetchListByQuery<T>(string str)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = str.ToString();
SqlDataReader dr;
try
{
conn.Open();
dr = cmd.ExecuteReader();
List<T> lst = new List<T>();
while (dr.Read())
{
T item = CommonFunctions.GetItem<T>(dr);
lst.Add(item);
}
return lst;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
// conn.Dispose();
}
}
// CRUD Opration By String Store Procedure
public void IUDbySP(string SPName, SqlParameter[] para)
{
SqlCommand cmd = GetCommand();
cmd.CommandText = SPName.ToString();
cmd.Parameters.AddRange(para);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
conn.Dispose();
}
}
// Fetch DataTable By Store Procedure
public DataTable FetchDataTableBySP(string Spname, SqlParameter[] para)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(para);
cmd.CommandText = Spname.ToString();
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
conn.Open();
da.Fill(dt);
return dt;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
conn.Dispose();
}
}
// Fetch DataSet By Store Procedure
public DataSet FetchDataSetBySP(string Spname, SqlParameter[] para)
{
DataSet ds = new DataSet();
SqlCommand cmd = GetCommand();
cmd.Parameters.AddRange(para);
cmd.CommandText = Spname.ToString();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
conn.Open();
da.Fill(ds);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
conn.Dispose();
}
}
// Fetch List By Store Procedure
public List<T> FetchListBySP<T>(string Spname, SqlParameter[] para)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(para);
cmd.CommandText = Spname.ToString();
SqlDataReader dr;
try
{
conn.Open();
dr = cmd.ExecuteReader();
List<T> lst = new List<T>();
while (dr.Read())
{
T item = CommonFunctions.GetItem<T>(dr);
lst.Add(item);
}
return lst;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
// conn.Dispose();
}
}
// Call By Store Procedure
public SqlCommand GetCommand()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
return cmd;
}
// Fetch DataTable By String Query With Parameter
public DataTable FetchDataTableByText(string Query, SqlParameter[] para)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddRange(para);
cmd.CommandText = Query.ToString();
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
conn.Open();
da.Fill(dt);
return dt;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
// conn.Dispose();
}
}
// Fetch List By String Query With Parameter
public List<T> FetchListByText<T>(string Query, SqlParameter[] para)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddRange(para);
cmd.CommandText = Query.ToString();
SqlDataReader dr;
try
{
conn.Open();
dr = cmd.ExecuteReader();
List<T> lst = new List<T>();
if (dr.HasRows)
{
while (dr.Read())
{
T item = CommonFunctions.GetItem<T>(dr);
lst.Add(item);
}
}
return lst;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
// conn.Dispose();
}
}
}
}
--------------------------------------------
PendotaAPI_Repository - DataServices - CreatePara.cs
--------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PendotaAPI_Repository.DataServices
{
public static class CreatePara
{
public static SqlParameter CreateParameter(this SqlParameter para, string paraName, string paraVal, int size = 50, ParameterDirection dir = ParameterDirection.Input)
{
para.ParameterName = paraName;
para.Value = paraVal;
para.Size = size;
para.SqlDbType = System.Data.SqlDbType.NVarChar;
para.Direction = dir;
return para;
}
public static SqlParameter CreateParameter(this SqlParameter para, string paraName, int paraVal, ParameterDirection dir = ParameterDirection.Input)
{
para.ParameterName = paraName;
para.Value = paraVal;
para.SqlDbType = System.Data.SqlDbType.Int;
para.Direction = dir;
return para;
}
public static SqlParameter CreateParameter(this SqlParameter para, string paraName, decimal paraVal, ParameterDirection dir = ParameterDirection.Input)
{
para.ParameterName = paraName;
para.Value = paraVal;
para.SqlDbType = System.Data.SqlDbType.Decimal;
para.Direction = dir;
return para;
}
public static SqlParameter CreateParameter(this SqlParameter para, string paraName, float paraVal, ParameterDirection dir = ParameterDirection.Input)
{
para.ParameterName = paraName;
para.Value = paraVal;
para.SqlDbType = System.Data.SqlDbType.Float;
para.Direction = dir;
return para;
}
public static SqlParameter CreateParameter(this SqlParameter para, string paraName, DateTime paraVal, ParameterDirection dir = ParameterDirection.Input)
{
para.IsNullable = true;
para.ParameterName = paraName;
para.Value = paraVal;
para.SqlDbType = System.Data.SqlDbType.DateTime;
para.Direction = dir;
return para;
}
public static SqlParameter CreateParameter(this SqlParameter para, string paraName, System.Data.DataTable paraVal, ParameterDirection dir = ParameterDirection.Input)
{
para.ParameterName = paraName;
para.Value = paraVal;
para.SqlDbType = System.Data.SqlDbType.Structured;
para.Direction = dir;
return para;
}
}
}
--------------------------------------------
PendotaAPI_Repository - DataServices - CommonFunctions.cs
--------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Drawing;
using System.IO;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.Web.UI;
using System.Reflection;
using System.Net.Mail;
using System.Configuration;
using System.Net;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
namespace PendotaAPI_Repository.DataServices
{
public static class CommonFunctions
{
// Convert To List
public static List<T> ConvertToList<T>(this DataTable dt)
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
//T item = GetItem<T>(row);
//data.Add(item);
}
return data;
}
// Convert To Class
public static T GetItem<T>(SqlDataReader dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
for (int i = 0; i < dr.FieldCount; i++)
{
foreach (PropertyInfo pro in temp.GetProperties())
{
if (pro.Name.ToLower() == "barcode")
{
var abc = "";
}
if (pro.Name.ToLower() == dr.GetName(i).ToLower())
{
if (!string.IsNullOrEmpty(Convert.ToString(dr[i])))
{
if (pro.PropertyType.Name == "String")
pro.SetValue(obj, Convert.ToString(dr[i]));
else if (pro.PropertyType.Name == "Byte[]" && string.IsNullOrEmpty(Convert.ToString(dr[i])))
pro.SetValue(obj, new byte[0]);
else
pro.SetValue(obj, dr[i]);
}
break;
}
}
}
return obj;
}
// Random String
public static string RandomString(int Size)
{
Random random = new Random();
string input = "abcdefghijklmnopqrstuvwxyz0123456789";
var chars = Enumerable.Range(0, Size).Select(x => input[random.Next(0, input.Length)]);
return new string(chars.ToArray());
}
// Encode Function
public static string Base64Encode(string plainText)
{
try
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
catch (Exception)
{
throw;
}
}
// Decode Function
public static string Base64Decode(string base64EncodedData)
{
try
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
catch (Exception)
{
throw;
}
}
// Convert DataTable to Json
public static string ConvertToJSON(this DataTable table, Boolean IsSkipTotalRow = true)
{
var list = new List<Dictionary<string, object>>();
foreach (DataRow row in table.Rows)
{
var dict = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
if (IsSkipTotalRow && col.ColumnName.ToLower() != "totalrows")
dict[col.ColumnName] = row[col];
}
list.Add(dict);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
return serializer.Serialize(list);
}
// Convert DataTable to Json
public static string GetJsonForDataTableJS(this DataTable dt)
{
StringBuilder sb = new StringBuilder();
string data = dt.ConvertToJSON();
sb.AppendLine("{\"data\":" + data);
sb.Append(",\"draw\":\"" + Convert.ToString(HttpContext.Current.Request.Form["draw"]) + "\"");
sb.Append(",\"recordsFiltered\":\"" + (dt.Rows.Count == 0 ? "0" : dt.Rows[0]["TotalRows"].ToString()) + "\"");
sb.Append(",\"recordsTotal\":\"" + (dt.Rows.Count == 0 ? "0" : dt.Rows[0]["TotalRows"].ToString()) + "\"}");
return sb.ToString();
}
}
}
PendotaAPI - Controller - CustomerController.cs
--------------------------------------------
using PendotaAPI_Repository.DTO;
using PendotaAPI_Repository.Service;
using PendotaAPI_Repository.ServiceContract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace PendotaAPI.Controllers
{
public class CustomerController : ApiController
{
private ICustomer_Repository _ICustomer_Repository;
public CustomerController()
{
this._ICustomer_Repository = new Customer_Repository();
}
[HttpGet]
[Route("api/Customer")]
//GET: api/Customer
public HttpResponseMessage Get()
{
try
{
List<Customer> curList = new List<Customer>();
curList = _ICustomer_Repository.Get();
HttpResponseMessage rea = Request.CreateResponse(HttpStatusCode.OK, curList.ToList());
return rea;
// return Ok(curList.AsEnumerable());
}
catch (Exception ex)
{
return null;
}
}
[Route("api/Customer/{id}")]
// GET: api/Customer/5
[HttpGet]
public Customer Get(int id)
{
return _ICustomer_Repository.GetCustomerById(id);
}
// POST: api/Customer
[HttpPost]
[Route("api/Customer")]
public void Post([FromBody]Customer objCustomer)
{
try
{
_ICustomer_Repository.Save(objCustomer);
}
catch (Exception ex)
{
throw;
}
}
// PUT: api/Customer/5
[HttpPut]
[Route("api/Customer/{id}")]
public void Put(int id, [FromBody]Customer objCustomer)
{
try
{
objCustomer.CustomerID = id;
_ICustomer_Repository.Save(objCustomer);
}
catch (Exception ex)
{
throw;
}
}
// DELETE: api/Customer/5
[HttpDelete]
[Route("api/Customer/{id}")]
public void Delete(int id)
{
try
{
_ICustomer_Repository.Delete(id);
}
catch (Exception ex)
{
throw;
}
}
}
}
--------------------------------------------
PendotaAPI - Web.config
--------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=301879
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6" />
<httpRuntime targetFramework="4.6" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<connectionStrings>
<add name="Dalc_Conn" connectionString="Data Source=DESKTOP-QANVEDT\SQLEXPRESS;Initial Catalog=PendotaDB;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
</customHeaders>
</httpProtocol>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers></system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
--------------------------------------------
PendotaAPI_Repository - DTO - Customer.cs
--------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PendotaAPI_Repository.DTO
{
public class Customer
{
[Key]
public int CustomerID { get; set; }
[Required(ErrorMessage = "Customer Name Required.")]
public string CustomerName { get; set; }
[Required(ErrorMessage = "Customer Phone Required.")]
public string CustomerPhone { get; set; }
[Required(ErrorMessage = "Customer Email Required.")]
public string CustomerEmail { get; set; }
[Required(ErrorMessage = "Country Required.")]
public int Country { get; set; }
public string Address { get; set; }
public string Zipcode { get; set; }
public bool Status { get; set; }
public string CityName { get; set; }
}
}
--------------------------------------------
PendotaAPI_Repository - Service- Customer_Repository.cs
--------------------------------------------
using PendotaAPI_Repository.DataServices;
using PendotaAPI_Repository.ServiceContract;
using PendotaAPI_Repository.DTO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace PendotaAPI_Repository.Service
{
public class Customer_Repository : ICustomer_Repository
{
// Get Customer List
public List<Customer> Get()
{
try
{
SqlParameter[] para = new SqlParameter[0];
return new dalc().FetchListBySP<Customer>("Usp_FetchCustomerList", para);
}
catch (Exception ex)
{
throw;
}
}
// Get Customer
public Customer GetCustomerById(int id)
{
try
{
SqlParameter[] para = new SqlParameter[1];
para[0] = new SqlParameter().CreateParameter("@CustomerID", id);
return new dalc().FetchListBySP<Customer>("Usp_FetchCustomer", para).FirstOrDefault();
}
catch (Exception ex)
{
throw;
}
}
// Get Customer Save
public void Save(Customer objCustomer)
{
try
{
SqlParameter[] para = new SqlParameter[7];
para[0] = new SqlParameter().CreateParameter("@CustomerID", objCustomer.CustomerID);
para[1] = new SqlParameter().CreateParameter("@CustomerName", objCustomer.CustomerName);
para[2] = new SqlParameter().CreateParameter("@CustomerPhone", objCustomer.CustomerPhone);
para[3] = new SqlParameter().CreateParameter("@CustomerEmail", objCustomer.CustomerEmail);
para[4] = new SqlParameter().CreateParameter("@Country", objCustomer.Country);
para[5] = new SqlParameter().CreateParameter("@Address", objCustomer.Address);
para[6] = new SqlParameter().CreateParameter("@Zipcode", objCustomer.Zipcode);
new dalc().IUDbySP("Usp_SaveCustomer", para);
}
catch (Exception ex)
{
throw;
}
}
// Get Customer Delete
public void Delete(int id)
{
try
{
SqlParameter[] para = new SqlParameter[1];
para[0] = new SqlParameter().CreateParameter("@CustomerID", id);
new dalc().IUDbySP("Usp_DeleteCustomer", para);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
--------------------------------------------
PendotaAPI_Repository - ServiceContract - ICustomer_Repository.cs
--------------------------------------------
using PendotaAPI_Repository.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PendotaAPI_Repository.ServiceContract
{
public interface ICustomer_Repository
{
List<Customer> Get();
Customer GetCustomerById(int id);
void Save(Customer objBank);
void Delete(int id);
}
}
--------------------------------------------
PendotaAPI_Repository - DataServices - dalc.cs
--------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Configuration;
namespace PendotaAPI_Repository.DataServices
{
public class dalc
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Dalc_Conn"].ConnectionString);
public dalc()
{
}
// CRUD Opration By String Query
public void IUDByQuery(string str)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = str;
//cmd.Parameters.AddRange(para);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Dispose();
}
}
// Fetch DataTable By String Query
public DataTable FetchDataTableByQuery(string str)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = str.ToString();
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
conn.Open();
da.Fill(dt);
return dt;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
// conn.Dispose();
}
}
// Fetch DataSet By String Query
public DataSet FetchDataSetByQuery(string str)
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandText = str.ToString();
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
conn.Open();
da.Fill(ds);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
conn.Dispose();
}
}
// Fetch List By String Query
public List<T> FetchListByQuery<T>(string str)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = str.ToString();
SqlDataReader dr;
try
{
conn.Open();
dr = cmd.ExecuteReader();
List<T> lst = new List<T>();
while (dr.Read())
{
T item = CommonFunctions.GetItem<T>(dr);
lst.Add(item);
}
return lst;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
// conn.Dispose();
}
}
// CRUD Opration By String Store Procedure
public void IUDbySP(string SPName, SqlParameter[] para)
{
SqlCommand cmd = GetCommand();
cmd.CommandText = SPName.ToString();
cmd.Parameters.AddRange(para);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
conn.Dispose();
}
}
// Fetch DataTable By Store Procedure
public DataTable FetchDataTableBySP(string Spname, SqlParameter[] para)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(para);
cmd.CommandText = Spname.ToString();
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
conn.Open();
da.Fill(dt);
return dt;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
conn.Dispose();
}
}
// Fetch DataSet By Store Procedure
public DataSet FetchDataSetBySP(string Spname, SqlParameter[] para)
{
DataSet ds = new DataSet();
SqlCommand cmd = GetCommand();
cmd.Parameters.AddRange(para);
cmd.CommandText = Spname.ToString();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
conn.Open();
da.Fill(ds);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
conn.Dispose();
}
}
// Fetch List By Store Procedure
public List<T> FetchListBySP<T>(string Spname, SqlParameter[] para)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(para);
cmd.CommandText = Spname.ToString();
SqlDataReader dr;
try
{
conn.Open();
dr = cmd.ExecuteReader();
List<T> lst = new List<T>();
while (dr.Read())
{
T item = CommonFunctions.GetItem<T>(dr);
lst.Add(item);
}
return lst;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
// conn.Dispose();
}
}
// Call By Store Procedure
public SqlCommand GetCommand()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
return cmd;
}
// Fetch DataTable By String Query With Parameter
public DataTable FetchDataTableByText(string Query, SqlParameter[] para)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddRange(para);
cmd.CommandText = Query.ToString();
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
conn.Open();
da.Fill(dt);
return dt;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
// conn.Dispose();
}
}
// Fetch List By String Query With Parameter
public List<T> FetchListByText<T>(string Query, SqlParameter[] para)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddRange(para);
cmd.CommandText = Query.ToString();
SqlDataReader dr;
try
{
conn.Open();
dr = cmd.ExecuteReader();
List<T> lst = new List<T>();
if (dr.HasRows)
{
while (dr.Read())
{
T item = CommonFunctions.GetItem<T>(dr);
lst.Add(item);
}
}
return lst;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
cmd.Parameters.Clear();
cmd.Dispose();
// conn.Dispose();
}
}
}
}
--------------------------------------------
PendotaAPI_Repository - DataServices - CreatePara.cs
--------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PendotaAPI_Repository.DataServices
{
public static class CreatePara
{
public static SqlParameter CreateParameter(this SqlParameter para, string paraName, string paraVal, int size = 50, ParameterDirection dir = ParameterDirection.Input)
{
para.ParameterName = paraName;
para.Value = paraVal;
para.Size = size;
para.SqlDbType = System.Data.SqlDbType.NVarChar;
para.Direction = dir;
return para;
}
public static SqlParameter CreateParameter(this SqlParameter para, string paraName, int paraVal, ParameterDirection dir = ParameterDirection.Input)
{
para.ParameterName = paraName;
para.Value = paraVal;
para.SqlDbType = System.Data.SqlDbType.Int;
para.Direction = dir;
return para;
}
public static SqlParameter CreateParameter(this SqlParameter para, string paraName, decimal paraVal, ParameterDirection dir = ParameterDirection.Input)
{
para.ParameterName = paraName;
para.Value = paraVal;
para.SqlDbType = System.Data.SqlDbType.Decimal;
para.Direction = dir;
return para;
}
public static SqlParameter CreateParameter(this SqlParameter para, string paraName, float paraVal, ParameterDirection dir = ParameterDirection.Input)
{
para.ParameterName = paraName;
para.Value = paraVal;
para.SqlDbType = System.Data.SqlDbType.Float;
para.Direction = dir;
return para;
}
public static SqlParameter CreateParameter(this SqlParameter para, string paraName, DateTime paraVal, ParameterDirection dir = ParameterDirection.Input)
{
para.IsNullable = true;
para.ParameterName = paraName;
para.Value = paraVal;
para.SqlDbType = System.Data.SqlDbType.DateTime;
para.Direction = dir;
return para;
}
public static SqlParameter CreateParameter(this SqlParameter para, string paraName, System.Data.DataTable paraVal, ParameterDirection dir = ParameterDirection.Input)
{
para.ParameterName = paraName;
para.Value = paraVal;
para.SqlDbType = System.Data.SqlDbType.Structured;
para.Direction = dir;
return para;
}
}
}
--------------------------------------------
PendotaAPI_Repository - DataServices - CommonFunctions.cs
--------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Drawing;
using System.IO;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.Web.UI;
using System.Reflection;
using System.Net.Mail;
using System.Configuration;
using System.Net;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
namespace PendotaAPI_Repository.DataServices
{
public static class CommonFunctions
{
// Convert To List
public static List<T> ConvertToList<T>(this DataTable dt)
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
//T item = GetItem<T>(row);
//data.Add(item);
}
return data;
}
// Convert To Class
public static T GetItem<T>(SqlDataReader dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
for (int i = 0; i < dr.FieldCount; i++)
{
foreach (PropertyInfo pro in temp.GetProperties())
{
if (pro.Name.ToLower() == "barcode")
{
var abc = "";
}
if (pro.Name.ToLower() == dr.GetName(i).ToLower())
{
if (!string.IsNullOrEmpty(Convert.ToString(dr[i])))
{
if (pro.PropertyType.Name == "String")
pro.SetValue(obj, Convert.ToString(dr[i]));
else if (pro.PropertyType.Name == "Byte[]" && string.IsNullOrEmpty(Convert.ToString(dr[i])))
pro.SetValue(obj, new byte[0]);
else
pro.SetValue(obj, dr[i]);
}
break;
}
}
}
return obj;
}
// Random String
public static string RandomString(int Size)
{
Random random = new Random();
string input = "abcdefghijklmnopqrstuvwxyz0123456789";
var chars = Enumerable.Range(0, Size).Select(x => input[random.Next(0, input.Length)]);
return new string(chars.ToArray());
}
// Encode Function
public static string Base64Encode(string plainText)
{
try
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
catch (Exception)
{
throw;
}
}
// Decode Function
public static string Base64Decode(string base64EncodedData)
{
try
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
catch (Exception)
{
throw;
}
}
// Convert DataTable to Json
public static string ConvertToJSON(this DataTable table, Boolean IsSkipTotalRow = true)
{
var list = new List<Dictionary<string, object>>();
foreach (DataRow row in table.Rows)
{
var dict = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
if (IsSkipTotalRow && col.ColumnName.ToLower() != "totalrows")
dict[col.ColumnName] = row[col];
}
list.Add(dict);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
return serializer.Serialize(list);
}
// Convert DataTable to Json
public static string GetJsonForDataTableJS(this DataTable dt)
{
StringBuilder sb = new StringBuilder();
string data = dt.ConvertToJSON();
sb.AppendLine("{\"data\":" + data);
sb.Append(",\"draw\":\"" + Convert.ToString(HttpContext.Current.Request.Form["draw"]) + "\"");
sb.Append(",\"recordsFiltered\":\"" + (dt.Rows.Count == 0 ? "0" : dt.Rows[0]["TotalRows"].ToString()) + "\"");
sb.Append(",\"recordsTotal\":\"" + (dt.Rows.Count == 0 ? "0" : dt.Rows[0]["TotalRows"].ToString()) + "\"}");
return sb.ToString();
}
}
}
No comments:
Post a Comment