public class BaseController<T,E,R> : ApiController, ICRUD<E> where T : class
where E:class
where R : class
{
#region ExtensionMethod
public virtual object UpdateAllExtension(RequestDTO objParamData)
{
return null;
}
public virtual object DeleteAllExtension(object objParamData)
{
return null;
}
public virtual object CreateAllExtension(RequestDTO objParamData)
{
return null;
}
#endregion
#region Protected Methods
#region ResponseData
/// <summary>
/// Transforming result in to the client acceptable DTO format.
/// </summary>
/// <param name="objParamResult">object instance...</param>
/// <returns>ResponseModel instance...</returns>
protected object ResponseData(object objParamResult)
{
if (null == objParamResult)
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "NODATA");
else if (objParamResult is Exception)
{
if (objParamResult is UnauthorizedAccessException)
{
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, ((Exception)objParamResult).Message, (Exception)objParamResult);
}
//else if (objParamResult is System.ServiceModel.CommunicationException)
//{
// if (((Exception)objParamResult).InnerException != null && ((Exception)objParamResult).InnerException.Message == "The remote server returned an error: (401) Unauthorized.")
// return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid credentials", (Exception)objParamResult);
// else
// Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, ((Exception)objParamResult).Message, (Exception)objParamResult);
//}
return Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, ((Exception)objParamResult).Message, (Exception)objParamResult);
}
ResponseModel objResponseModelDTO = new ResponseModel();
objResponseModelDTO.data = objParamResult;
return objResponseModelDTO;
}
#endregion
#endregion
public Type objEntity = typeof(T);
#region Create
/// <summary>
/// Create new record in the table
/// </summary>
/// <param name="objDTO">Table Model Entity</param>
/// <returns>Response Model</returns>
[HttpPost]
public object Create(RequestDTO objRequestDTO)
{
Type objBusinessType = typeof(T);
//GenericRepository<T> objGenericRepository = new GenericRepository<B>();
object objBusinessInstance = Activator.CreateInstance(objBusinessType);
E objDTO = (E)DeserializeObject(objRequestDTO.Entity);
if (objDTO == null)
return ResponseData("Entity value is null");
Object objValue = objBusinessType.GetMethod("Insert").Invoke(objBusinessInstance, new object[] { objDTO });
object obj3 = objBusinessType.GetMethod("SaveChanges").Invoke(objBusinessInstance, null);
object objNewValue = CreateAllExtension(objRequestDTO);
objValue = objNewValue == null ? objValue : objNewValue;
return ResponseData(objValue);
}
#endregion
#region Update
/// <summary>
/// Update a record in the table
/// </summary>
/// <param name="objDTO">Table Model Entity</param>
/// <returns>Response Model</returns>
[HttpPost]
public object Update(RequestDTO objRequestDTO)
{
Type objBusinessType = typeof(T);
// GenericRepository<T> objGenericRepository = new GenericRepository<B>();
object objBusinessInstance = Activator.CreateInstance(objBusinessType);
E objDTO = (E)DeserializeObject(objRequestDTO.Entity);
if (objDTO == null)
return ResponseData("Entity value is null");
objBusinessType.GetMethod("Update").Invoke(objBusinessInstance, new object[] { objDTO });
object objValue = objBusinessType.GetMethod("SaveChanges").Invoke(objBusinessInstance, null);
object objNewValue = UpdateAllExtension(objRequestDTO);
objValue = objNewValue == null ? objValue : objNewValue;
return ResponseData(objValue);
}
#endregion
[HttpGet]
public object Delete(int iValue)
{
Type objBusinessType = typeof(T);
// GenericRepository<T> objGenericRepository = new GenericRepository<B>();
object objBusinessInstance = Activator.CreateInstance(objBusinessType);
if (iValue == null)
return ResponseData("Value is null");
objBusinessType.GetMethod("Delete").Invoke(objBusinessInstance, new object[] { iValue });
object objValue = objBusinessType.GetMethod("SaveChanges").Invoke(objBusinessInstance, null);
object objNewValue = DeleteAllExtension(objValue);
objValue = objNewValue == null ? objValue : objNewValue;
return ResponseData(objValue);
}
[HttpGet]
public object FindById(int objId)
{
//Type objBusinessType = typeof(T);
GenericRepository<E> objGenericRepository = new GenericRepository<E>();
// object objBusinessInstance = Activator.CreateInstance(objBusinessType);
object objValue = objGenericRepository.GetType().GetMethod("GetByID").Invoke(objGenericRepository, new object[] { objId });
// object objValue = objBusinessType.GetMethod("GetByID").Invoke(objBusinessInstance, new object[] { objId });
// objBusinessType.GetMethod("SaveChanges").Invoke(objBusinessInstance, null);
return ResponseData(objValue);
}
[HttpPost]
[Action1DebugActionWebApiFilter]
public object FindAll(RequestDTO objRequestDTO)
{
Type objBusinessType = typeof(T);
// GenericRepository<T> objGenericRepository = new GenericRepository<B>();
object objBusinessInstance = Activator.CreateInstance(objBusinessType);
List<Filter> filter = new List<Filter>
{
new Filter { PropertyName = "Id" , Value = "10" ,Operation = Op .Equals, },
};
if (objRequestDTO == null)
objRequestDTO = new RequestDTO();
// objRequestDTO.Filter = filter;
Expression<Func<E, bool>> delegFilter = null;
// delegFilter = ExpressionBuilder.GetExpression<E>(filter);
delegFilter= ExpressionBuilder.GetExpression<E>(objRequestDTO.Filter);
Func<IQueryable<E>, IOrderedQueryable<E>> delegOrder=null;
//delegOrder = (Func<IQueryable<E>, IOrderedQueryable<E>>)GetOrderBy<UserDTO>("dUserId", "asc");
if(!string.IsNullOrEmpty(objRequestDTO.strOrderColumn))
delegOrder = (Func<IQueryable<E>, IOrderedQueryable<E>>)GetOrderBy<E>(objRequestDTO.strOrderColumn,objRequestDTO.strSortBy);
// Expression<Func<UserDTO, bool>> deleg = ExpressionBuilder.GetOrderExpression<UserDTO>(order);
object objValue = objBusinessType.GetMethod("Get").Invoke(objBusinessInstance, new object[] { delegFilter, delegOrder, "", objRequestDTO.offset, objRequestDTO.Max});
// objBusinessType.GetMethod("SaveChanges").Invoke(objBusinessInstance, null);
//List<Type> lst =new List<Type>();
//lst.Add(typeof(SubTask));
//lst.Add(typeof(CheckList));
//lst.Add(typeof(Company));
//System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(typeof(Task), lst.AsEnumerable());
//var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(Task), new System.Runtime.Serialization.DataContractSerializerSettings()
//{
// DataContractResolver = new System.Data.Entity.Core.Objects.ProxyDataContractResolver()
//});
//var ms = new System.IO.MemoryStream();
//serializer.WriteObject(ms, objValue);
//ms.Seek(0, SeekOrigin.Begin);
//var sr = new StreamReader(ms);
//var xml = sr.ReadToEnd();
return ResponseData(objValue);
}
internal static object DeserializeObject(object objEntity)
{
string TempJson = Newtonsoft.Json.JsonConvert.SerializeObject(objEntity);
Type objType = typeof(Newtonsoft.Json.JsonConvert);
MethodInfo[] arrt = typeof(Newtonsoft.Json.JsonConvert).GetMethods();
object objValue1 = arrt[40].MakeGenericMethod(typeof(E)).Invoke(null, new object[] { TempJson });
return objValue1;
}
public object FindByOwnder(int objId)
{
throw new NotImplementedException();
}
public static Func<IQueryable<T>, IOrderedQueryable<T>> GetOrderBy<T>(string orderColumn, string orderType)
{
Type typeQueryable = typeof(IQueryable<T>);
ParameterExpression argQueryable = Expression.Parameter(typeQueryable, "p");
var outerExpression = Expression.Lambda(argQueryable, argQueryable);
string[] props = orderColumn.Split('.');
IQueryable<T> query = new List<T>().AsQueryable<T>();
Type type = typeof(T);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = arg;
foreach (string prop in props)
{
PropertyInfo pi = type.GetProperty(prop, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
expr = Expression.Property(arg, orderColumn);
LambdaExpression lambda = Expression.Lambda(expr, arg);
string methodName = orderType == "asc" ? "OrderBy" : "OrderByDescending";
MethodCallExpression resultExp =
Expression.Call(typeof(Queryable), methodName, new Type[] { typeof(T),type }, outerExpression.Body, Expression.Quote(lambda));
var finalLambda = Expression.Lambda(resultExp, argQueryable);
return (Func<IQueryable<T>, IOrderedQueryable<T>>)finalLambda.Compile();
}
}
#region ExpressionBuilder
public static class ExpressionBuilder
{
private static MethodInfo containsMethod = typeof(string).GetMethod("Contains");
private static MethodInfo startsWithMethod =
typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
private static MethodInfo endsWithMethod =
typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) });
public static Expression<Func<T,
bool>> GetExpression<T>(IList<Filter> filters)
{
if (filters == null)
return null;
if (filters.Count == 0)
return null;
ParameterExpression param = Expression.Parameter(typeof(T), "t");
Expression exp = null;
if (filters.Count == 1)
exp = GetExpression<T>(param, filters[0]);
else if (filters.Count == 2)
exp = GetExpression<T>(param, filters[0], filters[1]);
else
{
while (filters.Count > 0)
{
var f1 = filters[0];
var f2 = filters[1];
if (exp == null)
exp = GetExpression<T>(param, filters[0], filters[1]);
else
exp = Expression.AndAlso(exp, GetExpression<T>(param, filters[0], filters[1]));
filters.Remove(f1);
filters.Remove(f2);
if (filters.Count == 1)
{
exp = Expression.AndAlso(exp, GetExpression<T>(param, filters[0]));
filters.RemoveAt(0);
}
}
}
return Expression.Lambda<Func<T, bool>>(exp, param);
}
private static Expression GetExpression<T>(ParameterExpression param, Filter filter)
{
MemberExpression member = Expression.Property(param, filter.PropertyName);
ConstantExpression constant = null;
if (member.Type.Name == "Int32")
{
Int32 iValue = Convert.ToInt32(filter.Value);
constant = Expression.Constant(iValue);
}
else if (member.Type.Name == "Int64")
{
Int64 iValue = Convert.ToInt64(filter.Value);
constant = Expression.Constant(iValue);
}
else
constant = Expression.Constant(filter.Value);
switch (filter.Operation)
{
case Op.Equals:
return Expression.Equal(member, constant);
case Op.NotEquals:
return Expression.NotEqual(member, constant);
case Op.GreaterThan:
return Expression.GreaterThan(member, constant);
case Op.GreaterThanOrEqual:
return Expression.GreaterThanOrEqual(member, constant);
case Op.LessThan:
return Expression.LessThan(member, constant);
case Op.LessThanOrEqual:
return Expression.LessThanOrEqual(member, constant);
case Op.Contains:
return Expression.Call(member, containsMethod, constant);
case Op.StartsWith:
return Expression.Call(member, startsWithMethod, constant);
case Op.EndsWith:
return Expression.Call(member, endsWithMethod, constant);
}
return null;
}
private static BinaryExpression GetExpression<T>
(ParameterExpression param, Filter filter1, Filter filter2)
{
Expression bin1 = GetExpression<T>(param, filter1);
Expression bin2 = GetExpression<T>(param, filter2);
return Expression.AndAlso(bin1, bin2);
}
}
#endregion
public class Action1DebugActionWebApiFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
List<string> lstHeaderValue = actionContext.Request.Headers.GetValues("Authorization").ToList();
if (lstHeaderValue == null)
throw new Exception("");
}
}