コード例 #1
0
        internal IEnumerable <TModel> GetData(object AuthorID = null, bool?isBlock = null, bool fromView = false)
        {
            var filters = new List <GenericDataFormat.FilterItems>();

            if (AuthorID != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property         = "AuthorID",
                    Operation        = GenericDataFormat.FilterOperations.Equal,
                    Value            = AuthorID,
                    LogicalOperation = GenericDataFormat.LogicalOperations.And
                });
            }
            var requestBody = new GenericDataFormat()
            {
                Filters = filters
            };

            if (fromView)
            {
                return(new AuthorModel <TModel>().GetView <TModel>(requestBody).PageItems);
            }
            else
            {
                return(new AuthorModel <TModel>().Get(requestBody));
            }
        }
コード例 #2
0
        // GET: SIMCards/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var filters = new List <GenericDataFormat.FilterItems>();

            filters.Add(new GenericDataFormat.FilterItems()
            {
                Property = "SIMCardId", Operation = GenericDataFormat.FilterOperations.Equal, Value = id
            });
            requestBody = new GenericDataFormat()
            {
                Filters = filters, Includes = new GenericDataFormat.IncludeItems()
                {
                    References = "SIMCardStatus"
                }
            };
            var items = new SIMCardModel <SIMCardViewModel>().Get(requestBody);

            if (items.Count < 1 || items.ElementAt(0) == null)
            {
                return(HttpNotFound());
            }

            var model = (SIMCardViewModel)items.ElementAt(0);

            model.BindCreate_Modify_User();

            return(View(model));
        }
コード例 #3
0
        public virtual IHttpActionResult GetView(GenericDataFormat data)
        {
            var     queryItems = GetWithOptions(data);
            dynamic pageItems  = null;
            string  typ        = typeof(T).FullName;

            if (queryItems is List <Object> )
            {
                pageItems = ((List <Object>)queryItems);
            }
            else
            {
                var query = (IQueryable <T>)queryItems;
                pageItems = query.ToList <T>();
            }

            //remove paging
            data.Paging = null;
            queryItems  = GetWithOptions(data);
            int TotalItemsCount = 0;

            if (queryItems is List <Object> )
            {
                TotalItemsCount = ((List <Object>)queryItems).Count();
                var ObjectsResult = new PaginationResult <Object>
                {
                    TotalItemsCount = TotalItemsCount,
                    PageItems       = pageItems
                };
                return(Content(HttpStatusCode.OK, ObjectsResult));
            }
            else
            {
                var query = (IQueryable <T>)queryItems;
                TotalItemsCount = query.Count();
            }

            //var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
            //string s = serializer.Serialize(new PaginationResult<T>
            //{
            //    TotalItemsCount = TotalItemsCount,
            //    PageItems = pageItems
            //});

            var result = new PaginationResult <T>
            {
                TotalItemsCount = TotalItemsCount,
                PageItems       = pageItems
            };

            //var resp = new HttpResponseMessage()
            //{
            //    Content =
            //            new StringContent(serializer.Serialize(result), System.Text.Encoding.UTF8, "application/json")

            //};

            return(Content(HttpStatusCode.OK, result));
            //return ResponseMessage(resp);
        }
コード例 #4
0
 public virtual IHttpActionResult Get(GenericDataFormat data)
 {
     GetAuthorization();
     if (!IsAuthorize(Actions.GetByOptions))
     {
         return(Content(HttpStatusCode.Unauthorized, "Unauthorized"));
     }
     if (data != null)
     {
         dynamic result = GetWithOptions(data);
         return(Content(HttpStatusCode.OK, result));
         //if (!(result is IQueryable<T>))
         //{
         //    return
         //}
         //else
         //{
         //    return Content(HttpStatusCode.OK, (List<object>)result);
         //}
     }
     else
     {
         return(Get());
     }
 }
コード例 #5
0
ファイル: UserModel.cs プロジェクト: AhmedHamdyHosny/AfaqyERP
        internal void Get_Create_Modify_User(int createUserId, int?modifyUserId, ref UserViewModel createUser, ref UserViewModel modifyUser)
        {
            var filters = new List <GenericDataFormat.FilterItems>();

            if (createUserId != 0)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property = "UserId", Operation = GenericDataFormat.FilterOperations.Equal, Value = createUserId, LogicalOperation = GenericDataFormat.LogicalOperations.Or
                });
            }

            if (modifyUserId != null && modifyUserId != 0)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property = "UserId", Operation = GenericDataFormat.FilterOperations.Equal, Value = createUserId
                });
            }
            var requestBody = new GenericDataFormat()
            {
                Filters = filters
            };
            var users = this.Get(requestBody);

            createUser = users.Cast <UserViewModel>().SingleOrDefault(x => x.UserId == createUserId);
            modifyUser = users.Cast <UserViewModel>().SingleOrDefault(x => x.UserId == modifyUserId);
        }
コード例 #6
0
        internal IEnumerable <TModel> GetData(int?userRoleId = null, int?userId = null, int?roleId = null, bool?isBlock = null, bool fromView = false)
        {
            var filters = new List <GenericDataFormat.FilterItems>();

            if (userRoleId != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property         = "UserRoleId",
                    Operation        = GenericDataFormat.FilterOperations.Equal,
                    Value            = userRoleId,
                    LogicalOperation = GenericDataFormat.LogicalOperations.And
                });
            }
            if (userId != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property         = "UserId",
                    Operation        = GenericDataFormat.FilterOperations.Equal,
                    Value            = userId,
                    LogicalOperation = GenericDataFormat.LogicalOperations.And
                });
            }
            if (roleId != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property         = "RoleId",
                    Operation        = GenericDataFormat.FilterOperations.Equal,
                    Value            = roleId,
                    LogicalOperation = GenericDataFormat.LogicalOperations.And
                });
            }

            if (isBlock != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property         = "IsBlock",
                    Operation        = GenericDataFormat.FilterOperations.Equal,
                    Value            = isBlock,
                    LogicalOperation = GenericDataFormat.LogicalOperations.And
                });
            }

            var requestBody = new GenericDataFormat()
            {
                Filters = filters
            };

            if (fromView)
            {
                return(new UserRoleModel <TModel>().GetView <TModel>(requestBody).PageItems);
            }
            else
            {
                return(new UserRoleModel <TModel>().Get(requestBody));
            }
        }
コード例 #7
0
        public virtual List <TModel> GetAsDDLst(string includeProperties, string sortByProperty, List <GenericDataFormat.FilterItems> filters = null, GenericDataFormat.SortType sortType = GenericDataFormat.SortType.Asc, bool GetByView = false)
        {
            var sorts = new List <GenericDataFormat.SortItems>();

            sorts.Add(new GenericDataFormat.SortItems()
            {
                Property = sortByProperty, SortType = sortType
            });
            //create request body parameters
            GenericDataFormat requestBody = new GenericDataFormat()
            {
                Includes = new GenericDataFormat.IncludeItems()
                {
                    Properties = includeProperties
                }, Sorts = sorts
            };

            requestBody.Filters = filters;
            if (!GetByView)
            {
                var lst = this.Get(requestBody);
                return(lst);
            }
            else
            {
                var lst = this.GetView <TModel>(requestBody).PageItems;
                return(lst);
            }
        }
コード例 #8
0
        public override IHttpActionResult GetGridView(GenericDataFormat data)
        {
            var controller = new ApiUserRoleViewController();

            controller.Request       = new HttpRequestMessage();
            controller.Configuration = new HttpConfiguration();
            return(controller.GetGridView(data));
        }
コード例 #9
0
        public override IHttpActionResult Export(GenericDataFormat data)
        {
            var controller = new ApiConferenceViewController();

            controller.Request       = new HttpRequestMessage();
            controller.Configuration = new HttpConfiguration();
            return(controller.Export(data));
        }
コード例 #10
0
        internal IEnumerable <TModel> GetData(object JournalVersionID = null, object JournalID = null, object JournalVolumeTypeID = null, bool?isBlock = null, bool fromView = false)
        {
            var filters = new List <GenericDataFormat.FilterItems>();

            if (JournalVersionID != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property         = "JournalVersionID",
                    Operation        = GenericDataFormat.FilterOperations.Equal,
                    Value            = JournalVersionID,
                    LogicalOperation = GenericDataFormat.LogicalOperations.And
                });
            }
            if (JournalID != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property         = "JournalID",
                    Operation        = GenericDataFormat.FilterOperations.Equal,
                    Value            = JournalID,
                    LogicalOperation = GenericDataFormat.LogicalOperations.And
                });
            }
            if (JournalVolumeTypeID != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property         = "JournalVolumeTypeID",
                    Operation        = GenericDataFormat.FilterOperations.Equal,
                    Value            = JournalVolumeTypeID,
                    LogicalOperation = GenericDataFormat.LogicalOperations.And
                });
            }
            if (isBlock != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property         = "IsBlock",
                    Operation        = GenericDataFormat.FilterOperations.Equal,
                    Value            = isBlock,
                    LogicalOperation = GenericDataFormat.LogicalOperations.And
                });
            }
            var requestBody = new GenericDataFormat()
            {
                Filters = filters
            };

            if (fromView)
            {
                return(new JournalVersionModel <TModel>().GetView <TModel>(requestBody).PageItems);
            }
            else
            {
                return(new JournalVersionModel <TModel>().Get(requestBody));
            }
        }
コード例 #11
0
        public JsonResult GetGridView(GenericDataFormat options)
        {
            var model = (PaginationResult <TIndexViewModel>)Activator.CreateInstance(typeof(PaginationResult <TIndexViewModel>));
            DelegatePreGetGridView delegatePreExecute = new DelegatePreGetGridView(FuncPreGetGridView);

            delegatePreExecute(ref model, options);
            DelegatePostGetGridView delegatePostExecute = new DelegatePostGetGridView(FuncPostGetGridView);

            return(delegatePostExecute(ref model));
        }
コード例 #12
0
        public virtual List <TModel> Get(GenericDataFormat requestBody)
        {
            string url = ApiServerUrl + ControllerRoute + "get";
            MyHttpRequestMessage request = new MyHttpRequestMessage(url, HttpMethod.Post)
            {
                RequestBody = new StringContent(JsonConvert.SerializeObject(requestBody), System.Text.Encoding.UTF8, "application/json")
            };
            var task = request.Execute <List <TModel> >();

            task.Wait();
            return(task.Result);
        }
コード例 #13
0
        public JsonResult GetInfo(GenericDataFormat Options)
        {
            //create instance List of TViewModel
            var model = (List <TViewModel>)Activator.CreateInstance(typeof(List <TViewModel>));

            if (Options.Filters != null)
            {
                dynamic instance = Activator.CreateInstance(typeof(TModel_TViewModel));
                model = instance.GetView <TViewModel>(Options).PageItems;
            }
            return(Json(model));
        }
コード例 #14
0
        public override void FuncPreExport(ref GenericDataFormat ExportRequestBody, ref string ExportFileName)
        {
            ExportFileName = "Sponsors.xlsx";
            string properties = "SponsorName,Shortcut,IsBlock";

            ExportRequestBody = new GenericDataFormat()
            {
                Includes = new GenericDataFormat.IncludeItems()
                {
                    Properties = properties,
                }
            };
        }
コード例 #15
0
        public override void FuncPreDetailsView(object id, ref List <SponsorDetailsViewModel> items)
        {
            filters = new List <GenericDataFormat.FilterItems>();
            filters.Add(new GenericDataFormat.FilterItems()
            {
                Property = "SponsorID", Operation = GenericDataFormat.FilterOperations.Equal, Value = id
            });
            var requestBody = new GenericDataFormat()
            {
                Filters = filters
            };

            items = new SponsorModel <SponsorDetailsViewModel>().Get(requestBody);
        }
コード例 #16
0
        public virtual IHttpActionResult GetGridView(GenericDataFormat data)
        {
            GetAuthorization();
            if (!IsAuthorize(Actions.GetGridView))
            {
                return(Content(HttpStatusCode.Unauthorized, "Unauthorized"));
            }
            var     queryItems = GetWithOptions(data);
            dynamic pageItems  = null;
            string  typ        = typeof(T).FullName;

            if (queryItems is List <Object> )
            {
                pageItems = ((List <Object>)queryItems);
            }
            else
            {
                var query = (IQueryable <T>)queryItems;
                pageItems = query.ToList <T>();
            }

            //remove paging
            data.Paging = null;
            queryItems  = GetWithOptions(data);
            int TotalItemsCount = 0;

            if (queryItems is List <Object> )
            {
                TotalItemsCount = ((List <Object>)queryItems).Count();
                var ObjectsResult = new PaginationResult <Object>
                {
                    TotalItemsCount = TotalItemsCount,
                    PageItems       = pageItems
                };
                return(Content(HttpStatusCode.OK, ObjectsResult));
            }
            else
            {
                var query = (IQueryable <T>)queryItems;
                TotalItemsCount = query.Count();
            }

            var result = new PaginationResult <T>
            {
                TotalItemsCount = TotalItemsCount,
                PageItems       = pageItems
            };

            return(Content(HttpStatusCode.OK, result));
        }
コード例 #17
0
        public ActionResult TestDesign()
        {
            requestBody = new GenericDataFormat()
            {
                Includes = new GenericDataFormat.IncludeItems()
                {
                    References = "SIMCardStatus"
                }
            };

            var model = new SIMCardModel <SIMCardViewModel>().Get(requestBody);

            return(View(model));
        }
コード例 #18
0
        internal IEnumerable <TModel> GetData(Guid?PublishPeriodID = null, string PublishPeriodName = null, bool?isBlock = null, bool fromView = false)
        {
            var filters = new List <GenericDataFormat.FilterItems>();

            if (PublishPeriodID != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property         = "PublishPeriodID",
                    Operation        = GenericDataFormat.FilterOperations.Equal,
                    Value            = PublishPeriodID,
                    LogicalOperation = GenericDataFormat.LogicalOperations.And
                });
            }
            if (PublishPeriodName != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property         = "PublishPeriodName",
                    Operation        = GenericDataFormat.FilterOperations.Equal,
                    Value            = PublishPeriodName,
                    LogicalOperation = GenericDataFormat.LogicalOperations.And
                });
            }
            if (isBlock != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property         = "IsBlock",
                    Operation        = GenericDataFormat.FilterOperations.Equal,
                    Value            = isBlock,
                    LogicalOperation = GenericDataFormat.LogicalOperations.And
                });
            }

            var requestBody = new GenericDataFormat()
            {
                Filters = filters
            };

            if (fromView)
            {
                return(new PublishPeriodModel <TModel>().GetView <TModel>(requestBody).PageItems);
            }
            else
            {
                return(new PublishPeriodModel <TModel>().Get(requestBody));
            }
        }
コード例 #19
0
        internal List <TModel> GetByView(int id)
        {
            var filters = new List <GenericDataFormat.FilterItems>();

            filters.Add(new GenericDataFormat.FilterItems()
            {
                Property  = "UserId",
                Operation = GenericDataFormat.FilterOperations.Equal,
                Value     = id
            });
            var requestBody = new GenericDataFormat()
            {
                Filters = filters
            };

            return(this.GetView <TModel>(requestBody).PageItems);
        }
コード例 #20
0
 public virtual IHttpActionResult Get(GenericDataFormat data)
 {
     GetAuthorization();
     if (!IsAuthorize(Actions.GetByOptions))
     {
         return(Content(HttpStatusCode.Unauthorized, "Unauthorized"));
     }
     if (data != null)
     {
         dynamic result = GetWithOptions(data);
         return(Content(HttpStatusCode.OK, result));
     }
     else
     {
         return(Get());
     }
 }
コード例 #21
0
        // GET: SIMCards
        public ActionResult Index()
        {
            if (TempData["AlertMessage"] != null)
            {
                ViewBag.AlertMessage = TempData["AlertMessage"];
            }
            requestBody = new GenericDataFormat()
            {
                Includes = new GenericDataFormat.IncludeItems()
                {
                    References = "SIMCardStatus"
                }
            };
            var model = new SIMCardModel <SIMCardViewModel>().Get(requestBody);

            return(View(model));
        }
コード例 #22
0
        public virtual IHttpActionResult Export(GenericDataFormat data)
        {
            GetAuthorization();
            if (!IsAuthorize(Actions.Export))
            {
                return(Content(HttpStatusCode.Unauthorized, "Unauthorized"));
            }
            List <object> result = null;

            if (data != null)
            {
                var tempResult = GetWithOptions(data);
                if (!(tempResult is List <object>))
                {
                    result = ((IQueryable <T>)tempResult).ToList <object>();
                }
                else
                {
                    result = tempResult;
                }
            }
            else
            {
                result = repo.Repo.Get(filter: DataConstrains).ToList <object>();
            }
            //export data to file
            var exportFilePath = new Export <T>(result).ExportData();

            if (!System.IO.File.Exists(exportFilePath))
            {
                return(Content(HttpStatusCode.InternalServerError, "Export process failed"));
            }
            else
            {
                HttpResponseMessage responseMessage = null;
                // Serve the file to the client
                responseMessage         = Request.CreateResponse(HttpStatusCode.OK);
                responseMessage.Content = new StreamContent(new System.IO.FileStream(exportFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read));
                responseMessage.Content.Headers.ContentType                 = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                responseMessage.Content.Headers.ContentDisposition          = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                responseMessage.Content.Headers.ContentDisposition.FileName = typeof(T).Name;
                return(ResponseMessage(responseMessage));
            }
        }
コード例 #23
0
        internal void Get_Create_Modify_User(Guid createUserId, Guid?modifyUserId, ref string CreateUser_FullName, ref string ModifyUser_FullName)
        {
            var filters = new List <GenericDataFormat.FilterItems>();

            if (createUserId != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property = "UserId", Operation = GenericDataFormat.FilterOperations.Equal, Value = createUserId, LogicalOperation = GenericDataFormat.LogicalOperations.Or
                });
            }

            if (modifyUserId != null)
            {
                filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property = "UserId", Operation = GenericDataFormat.FilterOperations.Equal, Value = createUserId
                });
            }
            var requestBody = new GenericDataFormat()
            {
                Filters = filters
            };
            var users = this.GetView <UserViewModel>(requestBody).PageItems;

            var createUser = users.SingleOrDefault(x => x.UserId == createUserId);

            if (createUser != null)
            {
                CreateUser_FullName = createUser.FullName;
            }
            if (modifyUserId != null)
            {
                var modifyUser = users.SingleOrDefault(x => x.UserId == modifyUserId);
                if (modifyUser != null)
                {
                    ModifyUser_FullName = modifyUser.FullName;
                }
            }
        }
コード例 #24
0
        public UserViewModel Login()
        {
            GenericDataFormat requestBody = new GenericDataFormat();

            requestBody.Filters = new List <GenericDataFormat.FilterItems>();
            requestBody.Filters.Add(new GenericDataFormat.FilterItems()
            {
                Property = "UserName", Value = this.UserName, Operation = GenericDataFormat.FilterOperations.Equal
            });
            UserViewModel user = new UserModel <UserViewModel>().GetView <UserViewModel>(requestBody).PageItems.SingleOrDefault();

            if (user != null)
            {
                //var pass = UserModel<UserViewModel>.GetHashPassword(this.UserName, this.Password);
                if (user.Password == UserModel <UserViewModel> .GetHashPassword(this.UserName, this.Password))
                {
                    return(user);
                }
            }

            return(null);
        }
コード例 #25
0
 public ActionResult Export()
 {
     try
     {
         requestBody = new GenericDataFormat()
         {
             Includes = new GenericDataFormat.IncludeItems()
             {
                 Properties = "SIMCardId,SerialNumber,GSM,SIMCardStatus.SIMCardStatusName_en", References = "SIMCardStatus"
             }
         };
         var fileBytes = new SIMCardModel <SIMCard>().Export(requestBody);
         return(File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "SIMCards.xlsx"));
     }
     catch (AggregateException ex)
     {
         if (ex.InnerException is UnauthorizedAccessException)
         {
             return(RedirectToAction("Unauthorized", "Login"));
         }
         throw ex;
     }
 }
コード例 #26
0
        public JsonResult GetDDL(GenericDataFormat Options, bool fromView = false)
        {
            var filters = Options.Filters;
            IEnumerable <Helper.CustomSelectListItem> model = null;

            if (fromView)
            {
                if (Options.Filters != null)
                {
                    dynamic instance = Activator.CreateInstance(typeof(TModel_TViewModel));
                    model = instance.GetDDL(filters: filters);
                }
            }
            else
            {
                if (Options.Filters != null)
                {
                    dynamic instance = Activator.CreateInstance(typeof(TModel_TDBModel));
                    model = instance.GetDDL(filters: filters);
                }
            }
            return(Json(model.ToList()));
        }
コード例 #27
0
        // POST: Controller/Export
        public virtual ActionResult Export(GenericDataFormat ExportRequestBody = null)
        {
            try
            {
                DelegatePreExport delegatePreExecute = new DelegatePreExport(FuncPreExport);
                delegatePreExecute(ref ExportRequestBody, ref this.ExportFileName);

                //create instance of TModel of TDBModel
                dynamic instance  = Activator.CreateInstance(typeof(TModel_TDBModel));
                var     fileBytes = instance.Export(ExportRequestBody);

                DelegatePostExport delegatePostExecute = new DelegatePostExport(FuncPostExport);
                return(delegatePostExecute(fileBytes, this.ExportFileName));
            }
            catch (AggregateException ex)
            {
                if (ex.InnerException is UnauthorizedAccessException)
                {
                    return(RedirectToAction("Unauthorized", "Login"));
                }
                throw ex;
            }
        }
コード例 #28
0
        public UserViewModel GetUserFromSession()
        {
            UserViewModel cUser = null;

            if (HttpContext.Current.Session != null && HttpContext.Current.Session[UserViewModel.SessionName] != null)
            {
                cUser = (UserViewModel)HttpContext.Current.Session[UserViewModel.SessionName];
            }

            //for test
            if (cUser == null)
            {
                var requestBody = new GenericDataFormat();
                requestBody.Filters = new List <GenericDataFormat.FilterItems>();
                requestBody.Filters.Add(new GenericDataFormat.FilterItems()
                {
                    Property = "UserId", Operation = GenericDataFormat.FilterOperations.Equal, Value = "5C8FBE12-69B2-4EB7-B116-201AEEBD862B"
                });
                cUser = new UserModel <UserViewModel>().GetView <UserViewModel>(requestBody).PageItems.SingleOrDefault();
                cUser.SaveUserToLocalStorage(true);
            }

            return(cUser);
        }
コード例 #29
0
        public virtual IHttpActionResult PutWithReference(T value)
        {
            GetAuthorization();
            if (!IsAuthorize(Actions.Put))
            {
                return(Content(HttpStatusCode.Unauthorized, "Unauthorized"));
            }
            //Get original Item by PK with references
            //get PK property
            string pkPropName = Repository <T> .GetPKColumns(repo.Repo._context).SingleOrDefault();

            object id = typeof(T).GetProperty(pkPropName).GetValue(value);
            //filter by pk
            List <GenericDataFormat.FilterItems> filters = new List <FilterItems>();

            filters.Add(new FilterItems()
            {
                Property = pkPropName, Operation = FilterOperations.Equal, Value = id, LogicalOperation = LogicalOperations.And
            });
            //get list references properites with ICollection,IEnumable,IList type
            var referenceProps = typeof(T).GetProperties()
                                 .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetInterfaces().Any(x => x.GetGenericTypeDefinition() == typeof(IEnumerable <>)));

            //execlude self reference
            referenceProps = referenceProps.Where(p => !p.PropertyType.GetInterfaces().Any(x => x == typeof(IEnumerable <T>)));
            GenericDataFormat requestBody = new GenericDataFormat()
            {
                Filters = filters, Includes = new IncludeItems()
                {
                    References = string.Join(",", referenceProps.Select(x => x.Name))
                }
            };
            //get item with all references
            var     queryItems = GetWithOptions(requestBody);
            dynamic Items      = null;

            if (queryItems is List <Object> )
            {
                Items = ((List <Object>)queryItems);
            }
            else
            {
                var query = (IQueryable <T>)queryItems;
                Items = query.ToList <T>();
            }
            if (Items != null && Items.Count == 1)
            {
                T originalItem = Items[0];
                foreach (var refProp in referenceProps)
                {
                    if (refProp.GetValue(value) != null)
                    {
                        //get reference type
                        Type refType = refProp.PropertyType.GetGenericArguments()[0];
                        //create Repository of reference type
                        var ref_repoType = typeof(Repository <>).MakeGenericType(refType);
                        ////create instance of Repository of reference type
                        dynamic ref_rep = Activator.CreateInstance(ref_repoType, repo.Repo._context);

                        //get reference pk
                        //set the parameters of method
                        object[] parameters = new object[] { repo.Repo._context };
                        //invoke GetPKColumns method in Repository class with paramters to get the PK column name
                        var method = ref_repoType.GetMethod("GetPKColumns", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                        //invoke GetFilter method with parameters
                        var ref_pks = (IEnumerable <string>)method.Invoke(null, parameters);
                        if (ref_pks != null && ref_pks.SingleOrDefault() != null)
                        {
                            string ref_PK = ref_pks.SingleOrDefault();
                            IEnumerable <object> refValue         = (IEnumerable <object>)refProp.GetValue(value);
                            IEnumerable <object> originalRefValue = (IEnumerable <object>)refProp.GetValue(originalItem);
                            foreach (var childItem in refValue)
                            {
                                var originalChildItem = originalRefValue
                                                        .Where(c => c.GetType().GetProperty(ref_PK).GetValue(c) == childItem.GetType().GetProperty(ref_PK).GetValue(childItem)
                                                               //&& c.GetType().GetProperty(ref_PK).GetValue(c) != null
                                                               && c.GetType().GetProperty(ref_PK).GetValue(c).ToString() != "0")
                                                        .SingleOrDefault();
                                // Is original child item with same ID in DB?
                                if (originalChildItem != null)
                                {
                                    //Call Detach method with parameters
                                    //set the parameters of method
                                    parameters = new object[] { originalChildItem };
                                    //invoke Detach method in Repository class with paramters to Detach old value
                                    method = ref_repoType.GetMethod("Detach");
                                    method.Invoke(ref_rep, parameters);
                                    //Call Update method with parameters
                                    //set the parameters of method
                                    parameters = new object[] { childItem };
                                    //invoke Update method in Repository class with paramters to Update old value to new value
                                    method = ref_repoType.GetMethod("UpdateSingle");
                                    method.Invoke(ref_rep, parameters);
                                }
                                else
                                {
                                    //Add new value
                                    //Call Insert method with parameters
                                    //set the parameters of method
                                    parameters = new object[] { childItem };
                                    //invoke GetPKColumns method in Repository class with paramters to get the PK column name
                                    method = ref_repoType.GetMethod("InsertSingle");
                                    method.Invoke(ref_rep, parameters);
                                }
                            }
                            foreach (var originalChildItem in
                                     originalRefValue.Where(c => c.GetType().GetProperty(ref_PK).GetValue(c).ToString() != "0").ToList())
                            {
                                // Are there child items in the DB which are NOT in the
                                // new child item collection anymore?
                                if (!refValue.Any(c => c.GetType().GetProperty(ref_PK).GetValue(c) == originalChildItem.GetType().GetProperty(ref_PK).GetValue(originalChildItem)))
                                {
                                    //Delete old value
                                    // Yes -> It's a deleted child item -> Delete
                                    //repo.Repo.Detach(originalChildItem);

                                    //Call Detach method with parameters
                                    //set the parameters of method
                                    parameters = new object[] { originalChildItem };
                                    //invoke Detach method in Repository class with paramters to Detach old value
                                    method = ref_repoType.GetMethod("Detach");
                                    method.Invoke(ref_rep, parameters);
                                    //Call Delete method with parameters
                                    //get deleted id
                                    var ref_delete_id = originalChildItem.GetType().GetProperty(ref_PK).GetValue(originalChildItem);
                                    //set the parameters of method
                                    parameters = new object[] { ref_delete_id };
                                    //invoke Delete method in Repository class with paramters to Delete old value by PK
                                    method = ref_repoType.GetMethod("DeleteSingle");
                                    method.Invoke(ref_rep, parameters);
                                }
                            }
                        }
                    }
                }

                // Update scalar/complex properties
                repo.Repo.Detach(originalItem);
                repo.Repo.Update(value);

                repo.Save();
                return(Content(HttpStatusCode.OK, value));
            }
            else
            {
                return(Content(HttpStatusCode.Unauthorized, "Unauthorized"));
            }
        }
コード例 #30
0
        private dynamic GetWithOptions(GenericDataFormat data)
        {
            dynamic result = null;
            Func <IQueryable <T>, IOrderedQueryable <T> > orderBy = null;
            List <SortItems>             thenByOrders             = null;
            dynamic                      includeProperties        = null;
            dynamic                      includeReference         = null;
            Expression <Func <T, bool> > filterExpr = null;
            int?pageNumber = null;
            int?pageSize   = null;

            //include reference
            if (data.Includes != null)
            {
                includeProperties = !string.IsNullOrEmpty(data.Includes.Properties) ?
                                    data.Includes.Properties.Split(',') :
                                    null;
                includeReference = data.Includes.References;
            }
            //filters
            filterExpr = Repository <T> .GetFilter(data.Filters);

            // check if there is adata access constrains
            if (DataConstrains != null)
            {
                //check if there is custom filterations
                if (filterExpr != null)
                {
                    //combine data access constrains to filters
                    filterExpr = filterExpr.AndAlso(DataConstrains);
                }
                else
                {
                    //set filteration as data access constrains
                    filterExpr = DataConstrains;
                }
            }
            //orderby
            if (data.Sorts != null && data.Sorts.Count > 0)
            {
                var sortItem = data.Sorts[0];
                orderBy = Repository <T> .GetOrderBy(sortItem.Property, sortItem.SortType);

                if (data.Sorts.Count > 1)
                {
                    thenByOrders = data.Sorts.Skip(1).ToList();
                }
            }
            //paging
            if (data.Paging != null)
            {
                pageNumber = data.Paging.PageNumber;
                pageSize   = data.Paging.PageSize;
                if (orderBy == null)
                {
                    IEnumerable <string> keyNames = Repository <T> .GetPKColumns(repo.Repo._context);

                    orderBy = Repository <T> .GetOrderBy(keyNames.ElementAt(0), GenericDataFormat.SortType.Asc);
                }
            }

            //order by
            //List<Expression<Func<T,object>>> thenSortsSelectors = null;
            //if (data.Sorts != null && data.Sorts.Count > 0)
            //{
            //    orderBy = Repository<T>.GetOrderBy(data.Sorts[0].Property, data.Sorts[0].SortType);
            //    thenSortsSelectors = new List<Expression<Func<T, object>>>();
            //    foreach (var sort in data.Sorts.Skip(1))
            //    {
            //        thenSortsSelectors.Add(Repository<T>.GetSelector(sort.Property));
            //    }
            //}
            //order by
            //if (data.Sorts != null && data.Sorts.Count > 0)
            //{
            //    orderBy = Repository<T>.GetOrderBy(data.Sorts[0].Property, data.Sorts[0].SortType);
            //    thenSorts = new List<Func<IQueryable<T>, IOrderedQueryable<T>>>();
            //    foreach (var sort in data.Sorts.Skip(1))
            //    {
            //        thenSorts.Add(Repository<T>.GetOrderBy(sort.Property, sort.SortType));
            //    }
            //}

            result = repo.Repo.GetWithOptions(includeProperties: includeProperties, includeReferences: includeReference,
                                              filter: filterExpr, orderBy: orderBy, thenByOrders: thenByOrders,
                                              pageNumber: pageNumber, pageSize: pageSize);

            return(result);
        }