Exemple #1
0
        public ActionResult Details(int id)
        {
            ISystemResponse error = new SystemResponse();
            var             store = _articleBll.GetArticle(id, error);

            return(View(store));
        }
        public async Task <SystemResponse> DeleteByIdAsync(string accessToken, int id)
        {
            SystemResponse systemResponse = new SystemResponse();

            client.DefaultRequestHeaders.Add("access_token", accessToken);

            var response = await client.DeleteAsync(apiUrl + "delete/" + id);

            switch (response.StatusCode)
            {
            case HttpStatusCode.Unauthorized:
                systemResponse = SystemResponse.AccessDenied;
                break;

            case HttpStatusCode.NotFound:
                systemResponse = SystemResponse.NotFound;
                break;

            case HttpStatusCode.OK:
                systemResponse = SystemResponse.Success;
                break;

            default:
                break;
            }
            return(systemResponse);
        }
Exemple #3
0
        public IHttpActionResult Get(string storeId)
        {
            int  storeIdConverted;
            bool isNumeric = int.TryParse(storeId, out storeIdConverted);

            if (!isNumeric)
            {
                var errorResponse = new ServiceErrorModel {
                    error_msg = "Bad Request", error_code = 400, success = false
                };
                return(Ok(errorResponse));
            }

            ISystemResponse error    = new SystemResponse();
            var             articles = _repository.GetArticlesByStoreId(storeIdConverted, error);
            var             response = _modelFactory.Create(articles);


            if (!articles.Any())
            {
                var errorResponse = new ServiceErrorModel {
                    error_msg = "Record not Found", error_code = 404, success = false
                };
                return(Ok(errorResponse));
            }


            return(Ok(response));
        }
        public async Task <SystemResponse> RemovePost(long postId)
        {
            Post postObject = _dataContext.Set <Post>()
                              .AsTracking()
                              .FirstOrDefault(p => p.Id == postId);

            try
            {
                if (postObject == null)
                {
                    throw new RecordNotFoundException($"Post is not found {postId}");
                }
                _dataContext.Entry(postObject).State = EntityState.Deleted;
                await _dataContext.SaveChangesAsync();

                return(SystemResponse.SuccessResponse("Success"));
            }
            catch (DbUpdateException ex)
            {
                _logger.LogError(ex, "Update post failed");
                _dataContext.Entry(postObject).Reload();
                throw new UpdateFailedException("Update post failed");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Update post failed");
                throw new UpdateFailedException("Update post failed");
            }
        }
        public async Task <SystemResponse> UpdatePost(Post updatePost)
        {
            Post postObject = _dataContext.Set <Post>()
                              .AsTracking()
                              .FirstOrDefault(p => p.Id == updatePost.Id);

            try
            {
                if (postObject == null)
                {
                    throw new RecordNotFoundException($"Post is not found {updatePost.Id}");
                }
                _dataContext.Entry(postObject).CurrentValues.SetValues(updatePost);
                await _dataContext.SaveChangesAsync();

                return(SystemResponse.SuccessResponse("Success"));
            }
            catch (DbUpdateException ex)
            {
                _logger.LogError(ex, "Update post failed");
                _dataContext.Entry(postObject).Reload();
                throw new UpdateFailedException("Update post failed");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Update post failed");
                throw new UpdateFailedException("Update post failed");
            }
        }
Exemple #6
0
        // GET: Article
        public ActionResult Index()
        {
            ISystemResponse error  = new SystemResponse();
            var             stores = _articleBll.GetArticles(error);

            return(View(stores));
        }
Exemple #7
0
 public override void OnLoad(HttpContext context)
 {
     base.OnLoad(context);
     requestBody             = new RequestBody();
     requestBody.accessToken = context.Request["accessToken"];
     if (requestBody.accessToken == null || requestBody.accessToken.Trim().Length == 0)
     {
         SystemResponse.Output(SystemResponse.TYPE_NULLPARAMETER, out statusCode, out responseJson);
     }
     else
     {
         //验证用户
         TokenHelper    token          = new TokenHelper();
         UserTokenModel userTokenModel = token.getUserToken(requestBody.accessToken);
         if (userTokenModel == null)
         {
             SystemResponse.Output(SystemResponse.TYPE_EXPIRE, out statusCode, out responseJson);
         }
         else
         {
             object model = new object();
             if (model != null)
             {
                 responseBody = new ResponseBody();
                 responseJson = JsonConvert.SerializeObject(responseBody, Formatting.Indented);
             }
             else
             {
                 SystemResponse.Output(SystemResponse.TYPE_NULL, out statusCode, out responseJson);
             }
         }
     }
 }
Exemple #8
0
        private void ProcessPingRequest(Ping request)
        {
            byte[] encodedResponse;

            switch (request.RequestType)
            {
            case "Ping":
                var ping = new Ping {
                    RequestType = "Ping"
                };
                encodedResponse = _messageHandler.ObjectToByteArray(ping);
                _server.ChatRooms[Server.BaseChatRoomId].SendToSpecificUser(encodedResponse, _user);
                break;

            case "Kill":
                //Remove user from list
                _server.ChatRooms[Server.BaseChatRoomId].Users.Remove(_user);
                _user.Client.Close();

                //Send response to rest of room informing of user disconnect.
                //If we implement a listen to replace CheckAllActiveUsersInRoom()
                //We can remove this call from here

                var sr = new SystemResponse
                {
                    Message = _user.UserName + " has left the chat."
                };
                encodedResponse = _messageHandler.ObjectToByteArray(sr);
                _server.ChatRooms[Server.BaseChatRoomId].SendToAllUsers(encodedResponse);
                break;
            }
        }
        public async Task <SystemResponse> UpdateAsync(string accessToken, UpdateArticle article)
        {
            SystemResponse systemResponse = new SystemResponse();

            var data = JsonConvert.SerializeObject(article);
            var body = new StringContent(data, Encoding.UTF8, "application/json");

            client.DefaultRequestHeaders.Add("access_token", accessToken);

            var response = await client.PutAsync(apiUrl + "update", body);

            switch (response.StatusCode)
            {
            case HttpStatusCode.Unauthorized:
                systemResponse = SystemResponse.AccessDenied;
                break;

            case HttpStatusCode.NotFound:
                systemResponse = SystemResponse.NotFound;
                break;

            case HttpStatusCode.OK:
                systemResponse = SystemResponse.Success;
                break;

            default:
                break;
            }

            return(systemResponse);
        }
        public BillsOfLadingReferenceCharges GetBillOfLadingReferenceCharges(ICollection<BillOfLadingChargeRequest> chargeRequests)
        {
            var AdvantumWebService = ConfigurationManager.AppSettings["AdvantumWS"];

            var client = new RestClient(AdvantumWebService);
            var request = new RestRequest("getBlRefCharges.php", Method.GET);
            client.ClearHandlers();
            client.AddHandler("application/xml", new XmlDeserializer());

            string blReference = null;
            string storageTo = null;

            foreach (var item in chargeRequests)
            {
                blReference = string.IsNullOrEmpty(blReference) ? item.BLReferenceNumber.ToString() : blReference + "*" + item.BLReferenceNumber;
                storageTo = string.IsNullOrEmpty(storageTo) ? item.StorageToDate.ToString("yyyyMMdd") : storageTo + "*" + item.StorageToDate.ToString("yyyyMMdd");
            }

            request.AddParameter("blreference", blReference);
            request.AddParameter("storageto", storageTo);

            var httpResponse = client.Execute(request);

            var systemResponse = new SystemResponse<BillsOfLadingReferenceCharges>();

            //this will throw fault exceptions if it failscd
            systemResponse = DeserializationHelpers.ProcessWebServiceResponse<BillsOfLadingReferenceCharges>(httpResponse);

            //otherwise results will be returned as per usual
            return systemResponse.Result;
        }
        public CustomerBillsOfLading GetCustomerBillsOfLading(UserDetails userDetails)
        {
            //check input methods here
            //user details are both not null
            //throw fault exception
            ValidationHelpers.ValidateUserDetails(userDetails);

            var AdvantumWebService = ConfigurationManager.AppSettings["AdvantumWS"];

            var httpRequestclient = new RestClient(AdvantumWebService);
            var webServiceMethodRequest = new RestRequest("GetCustomerBls.php", Method.GET);
            httpRequestclient.ClearHandlers();
            httpRequestclient.AddHandler("application/xml", new XmlDeserializer());

            webServiceMethodRequest.AddParameter("username", userDetails.UserName);
            webServiceMethodRequest.AddParameter("password", userDetails.PassWord);

            var httpResponse = httpRequestclient.Execute(webServiceMethodRequest);

            var systemResponse = new SystemResponse<CustomerBillsOfLading>();

            //this will throw fault exceptions if it failscd
            systemResponse = DeserializationHelpers.ProcessWebServiceResponse<CustomerBillsOfLading>(httpResponse);

            //otherwise results will be returned
            return systemResponse.Result;
        }
 public override void OnLoad(HttpContext context)
 {
     base.OnLoad(context);
     requestBody             = new RequestBody();
     requestBody.accessToken = context.Request["accessToken"];
     requestBody.page        = Convert.ToInt32(context.Request["page"]);
     requestBody.pageSize    = Convert.ToInt32(context.Request["pageSize"]);
     requestBody.oid         = Convert.ToInt32(context.Request["oid"]);
     if (requestBody.accessToken == null || requestBody.accessToken.Trim().Length == 0 || requestBody.oid == 0)
     {
         SystemResponse.Output(SystemResponse.TYPE_NULLPARAMETER, out statusCode, out responseJson);
     }
     else
     {
         //验证用户
         TokenHelper    token          = new TokenHelper();
         UserTokenModel userTokenModel = token.getUserToken(requestBody.accessToken);
         if (userTokenModel == null)
         {
             SystemResponse.Output(SystemResponse.TYPE_EXPIRE, out statusCode, out responseJson);
         }
         else
         {
             ModelAdo <OrderSupplierModel> orderModel = new ModelAdo <OrderSupplierModel>();
             List <OrderSupplierModel>     models     = null;
             int pagenumber = requestBody.page == 0 ? 1 : requestBody.page;
             int totalCount = 1;
             orderModel.PageSize = requestBody.pageSize == 0 ? orderModel.PageSize : requestBody.pageSize;
             if (requestBody.oid == 0)
             {
                 models = orderModel.GetList(pagenumber, " cuid=?cuid ", "", out totalCount, "",
                                             new MySqlParameter("?cuid", userTokenModel.uid)
                                             );
             }
             else
             {
                 models = orderModel.GetList(pagenumber, " cuid=?cuid AND oid=?oid", "", out totalCount, "",
                                             new MySqlParameter("?cuid", Convert.ToInt32(userTokenModel.uid)),
                                             new MySqlParameter("?oid", requestBody.oid)
                                             );
             }
             if (models.Count >= 1)
             {
                 responseBody = new ResponseBody
                 {
                     page      = 1,
                     pageTotal = (totalCount + orderModel.PageSize - 1) / orderModel.PageSize,
                     total     = totalCount,
                     suppliers = models
                 };
                 responseJson = JsonConvert.SerializeObject(responseBody, Formatting.Indented);
             }
             else
             {
                 SystemResponse.Output(SystemResponse.TYPE_NULL, out statusCode, out responseJson);
             }
         }
     }
 }
Exemple #13
0
        public ActionResult Create()
        {
            ISystemResponse   error  = new SystemResponse();
            List <StoreModel> stores = _storeBll.GetStores(error);

            ViewBag.store_id = new SelectList(stores, "Id", "name");
            return(View());
        }
Exemple #14
0
        /// <summary>
        /// Generates the system-specific response format that is unique for all responses.
        /// </summary>
        /// <typeparam name="T">The DTO data type to be serialized and sent as data object.</typeparam>
        /// <param name="request">Current request in context.</param>
        /// <param name="statusCode">The status code to be sent to the client.</param>
        /// <param name="data">The response data to be sent to the client.</param>
        /// <param name="errorMessage">The message describing the error that occured.</param>
        /// <param name="subCode">Exception code as returned by JService.</param>
        /// <returns>HTTP response message.</returns>
        private static HttpResponseMessage SystemResponse <T>(this HttpRequestMessage request, SystemStatusCode statusCode, T data, string errorMessage, int subCode) where T : class
        {
            var response = new SystemResponse <T> {
                Status = statusCode, Data = data, Error = errorMessage, SubStatus = subCode
            };

            return(request.CreateResponse((HttpStatusCode)statusCode, response));
        }
Exemple #15
0
        public IHttpActionResult Get()
        {
            ISystemResponse error    = new SystemResponse();
            var             articles = _repository.GetArticles(error);
            var             response = _modelFactory.Create(articles);

            return(Ok(response));
        }
        public IHttpActionResult Put(Store store)
        {
            ISystemResponse error    = new SystemResponse();
            bool            updated  = _repository.UpdateStore(store, error);
            var             response = _modelFactory.Create(updated, error.Message);

            return(Ok(response));
        }
Exemple #17
0
        public IHttpActionResult Delete(int articleId)
        {
            ISystemResponse error    = new SystemResponse();
            bool            deleted  = _repository.DeleteArticle(articleId, error);
            var             response = _modelFactory.Create(deleted, error.Message);

            return(Ok(response));
        }
Exemple #18
0
        public IHttpActionResult Post(Article article)
        {
            ISystemResponse error    = new SystemResponse();
            bool            created  = _repository.CreateArticle(article, error);
            var             response = _modelFactory.Create(created, error.Message);

            return(Ok(response));
        }
        public override void OnLoad(HttpContext context)
        {
            base.OnLoad(context);
            requestBody             = new RequestBody();
            requestBody.userName    = context.Request["userName"];
            requestBody.userPwd     = context.Request["userPwd"];
            requestBody.userType    = context.Request["userType"];
            requestBody.bpuserid    = context.Request["bpuserid"];
            requestBody.channelid   = context.Request["channelid"];
            requestBody.deviceToken = context.Request["deviceToken"];
            requestBody.deviceType  = context.Request["deviceType"];
            if (requestBody.userType == null || requestBody.userName == null || requestBody.userPwd == null)
            {
                SystemResponse.Output(SystemResponse.TYPE_NULLPARAMETER, out statusCode, out responseJson);
            }
            else
            {
                string password = StringHelper.StringToMD5(requestBody.userPwd);
                ModelAdo <UserModel> userModel = new ModelAdo <UserModel>();
                UserModel            model     = userModel.GetModel(" rid=?rid and name =?name and password=?password", "",
                                                                    new MySqlParameter("?rid", requestBody.userType),
                                                                    new MySqlParameter("?name", requestBody.userName),
                                                                    new MySqlParameter("?password", password));

                if (model == null)
                {
                    SystemResponse.Output(SystemResponse.TYPE_LOGIN_ERROR, out statusCode, out responseJson);
                }
                else
                {
                    DateTime       dt             = DateTime.Now;
                    string         accessToken    = StringHelper.StringToMD5(dt.ToString());
                    TokenHelper    token          = new TokenHelper();
                    UserTokenModel modelUserToken = new UserTokenModel();
                    modelUserToken.uid         = model.id.ToString();
                    modelUserToken.rid         = model.rid;
                    modelUserToken.accessToken = accessToken;
                    modelUserToken.bpuserId    = requestBody.bpuserid;
                    modelUserToken.channelId   = requestBody.channelid;
                    modelUserToken.deviceToken = requestBody.deviceToken;
                    modelUserToken.deviceType  = Convert.ToInt32(requestBody.deviceType);
                    modelUserToken.loginTime   = StringHelper.ConvertDateTimeInt(DateTime.Now);
                    modelUserToken.isLogin     = 1;
                    token.updateToken(modelUserToken);

                    responseBody = new ResponseBody
                    {
                        accessToken = accessToken,
                        uid         = model.id.ToString(),
                        userName    = model.name,
                        nickName    = model.nickname,
                        userAvatar  = model.avatar,
                        userType    = model.rid
                    };
                    responseJson = JsonConvert.SerializeObject(responseBody, Formatting.Indented);
                }
            }
        }
        public IHttpActionResult Get(int storeId)
        {
            ISystemResponse error    = new SystemResponse();
            var             store    = _repository.GetStoreById(storeId, error);
            var             response = new StoreResponseModel {
                store = _modelFactory.Create(store)
            };

            return(Ok(response));
        }
Exemple #21
0
        public IHttpActionResult Get(int articleId, bool bit)
        {
            ISystemResponse error    = new SystemResponse();
            var             article  = _repository.GetArticleById(articleId, error);
            var             response = new ArticleResponseModel {
                article = article
            };

            return(Ok(response));
        }
Exemple #22
0
        public ActionResult Edit(int id)
        {
            ISystemResponse   error   = new SystemResponse();
            var               article = _articleBll.GetArticle(id, error);
            List <StoreModel> stores  = _storeBll.GetStores(error);

            ViewBag.store_id = new SelectList(stores, "Id", "name", article.store_id);

            return(View(article));
        }
Exemple #23
0
        /// <summary>
        /// Get the current solar system
        /// </summary>
        /// <returns>Returns a solarsystem object on success, null on failure</returns>
        public SolarSystem getSolarSystem()
        {
            SystemResponse sresp = (SystemResponse)com.sendCall(FunctionCallFactory.CALLS.GETSYSTEMINFORMATION, Response.RESPONSES.SOLARYSYSTEMRESPONSE);

            if (sresp == null)
            {
                return(null);
            }

            return(new SolarSystem(sresp.Name, sresp.Info));
        }
Exemple #24
0
        public ActionResult DeleteConfirmed(int id)
        {
            ISystemResponse error   = new SystemResponse();
            bool            deleted = _storeBll.DeleteStore(id, error);

            if (deleted)
            {
                return(RedirectToAction("Index"));
            }

            return(View());
        }
Exemple #25
0
        public ActionResult Edit(StoreModel store)
        {
            ISystemResponse error   = new SystemResponse();
            bool            updated = _storeBll.UpdateStore(store, error);

            if (updated)
            {
                return(RedirectToAction("Index"));
            }

            return(View());
        }
Exemple #26
0
        public ActionResult Edit(ArticleModel article)
        {
            ISystemResponse error   = new SystemResponse();
            bool            updated = _articleBll.UpdateArticle(article, error);

            if (updated)
            {
                return(RedirectToAction("Index"));
            }

            return(View());
        }
        internal static int WeightResponse(int currentValue, int limit, SystemResponse systemResponse)
        {
            switch (systemResponse)
            {
            case SystemResponse.Linear:
                return((int)((limit - currentValue) / (double)limit * 99) + 1);

            case SystemResponse.FirstOrder:
                return((int)Math.Ceiling(Math.Exp(-currentValue * _k / limit) * 100));

            default:
                throw new ArgumentOutOfRangeException(nameof(systemResponse), systemResponse, null);
            }
        }
        private async Task RunSystem()
        {
            _runSystem = true;
            while (_runSystem)
            {
                // check for token refresh required
                if (localSettings.Values["access_token"] == null || localSettings.Values["access_token_expire"] == null ||
                    !IsTokenValid(Convert.ToDateTime(localSettings.Values["access_token_expire"].ToString())))
                {
                    if (await GetAPIToken() == null)
                    {
                        _runSystem = false;
                        NewSystemErrorArgs args = new NewSystemErrorArgs();
                        args.systemError = SystemError.no_connection;
                        OnNewSystemError(args);
                        break;
                    }
                }
                // get the status
                SystemStatus systemStatus = await CashGenicAPIService.GetStatus(localSettings.Values["access_token"].ToString());

                if (systemStatus == null)
                {
                    _runSystem = false;
                    NewSystemErrorArgs args = new NewSystemErrorArgs();
                    args.systemError = SystemError.no_connection;
                    OnNewSystemError(args);
                    break;
                }
                ParseStatus(systemStatus.Events);


                // any commands
                if (_cancelPayment)
                {
                    _cancelPayment = false;
                    SystemResponse systemResponse = await CashGenicAPIService.CancelSession(localSettings.Values["access_token"].ToString());
                }
                if (_closeSession)
                {
                    _closeSession = false;
                    SystemResponse systemResponse = await CashGenicAPIService.EndSession(localSettings.Values["access_token"].ToString());
                }


                // poll delay
                Thread.Sleep(500);
            }
        }
Exemple #29
0
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ISystemResponse error = new SystemResponse();
            StoreModel      store = _storeBll.GetStore(id.Value, error);

            if (store == null)
            {
                return(HttpNotFound());
            }
            return(View(store));
        }
Exemple #30
0
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ISystemResponse error   = new SystemResponse();
            Article         article = _articleBll.GetArticle(id.Value, error);

            if (article == null)
            {
                return(HttpNotFound());
            }
            return(View(article));
        }
        public async Task <SystemResponse> StartRefundSession(int requestValue)
        {
            if (localSettings.Values["access_token"] == null || localSettings.Values["access_token_expire"] == null ||
                !IsTokenValid(Convert.ToDateTime(localSettings.Values["access_token_expire"].ToString())))
            {
                if (await GetAPIToken() == null)
                {
                    return(SystemResponse.InvalidCredentials);
                }
            }

            SystemResponse ret = await CashGenicAPIService.StartRefundSession(localSettings.Values["access_token"].ToString(), requestValue);

            return(ret);
        }
Exemple #32
0
        public void RemoveInvalidUsers(List <User> users, int chatRoomId)
        {
            while (users.Any(u => u.IsUserValid == false))
            {
                var invalidUser = users.First(u => u.IsUserValid == false);
                users.Remove(invalidUser);

                var sr = new SystemResponse
                {
                    Message = invalidUser.UserName + " has left the chat."
                };
                var encodedResponse = _messageHandler.ObjectToByteArray(sr);
                ChatRooms[chatRoomId].SendToAllUsers(encodedResponse);
            }
        }
        public SystemResponse<string> CreatePersonalProtectiveEquipmentTransaction(PersonalProtectiveEquipmentTransaction personalProtectiveEquipmentTransaction)
        {
            var transactionType = GetTransactionType(personalProtectiveEquipmentTransaction.TransactionTypeId);

            var currentModelInventory = GetPersonalProtectiveEquipmentCategoryTypeModelInventory(personalProtectiveEquipmentTransaction.PersonalProtectiveEquipmentCategoryTypeModelId);

            SystemResponse<string> response = new SystemResponse<string>("No Error");
            //if its an outgoing transaction check the inventory levels
            //if the amount in current inventory exceeds an error must be returned

            //if transaction is outgoing check inventory levels first
            //check the direction of the transaction
            if (transactionType.TransactionDirection.Name == "Outgoing")
            {
                //make sure inventory being issued doesnt exceed existing quantity
                if (currentModelInventory.Quantity < personalProtectiveEquipmentTransaction.Quantity)
                {
                    response.ErrorMessages.Add("There aren't enough items in the inventory to meet that quantity.");
                    response.ErrorOccurred = true;
                }
                else
                {
                    currentModelInventory.Quantity -= personalProtectiveEquipmentTransaction.Quantity;
                    currentModelInventory.PersonalProtectiveEquipmentCategoryTypeModel = null;
                    UpdatePersonalProtectiveEquipmentCategoryTypeModelInventory(currentModelInventory);
                    _dataManager.CreatePersonalProtectiveEquipmentTransaction(personalProtectiveEquipmentTransaction);
                }
            }
            else if (transactionType.TransactionDirection.Name == "Incoming")
            {
                currentModelInventory.Quantity += personalProtectiveEquipmentTransaction.Quantity;
                currentModelInventory.PersonalProtectiveEquipmentCategoryTypeModel = null;

                UpdatePersonalProtectiveEquipmentCategoryTypeModelInventory(currentModelInventory);

                _dataManager.CreatePersonalProtectiveEquipmentTransaction(personalProtectiveEquipmentTransaction);
            }
            else //neutral transaction
            {
                _dataManager.CreatePersonalProtectiveEquipmentTransaction(personalProtectiveEquipmentTransaction);
            }

            return response;
            //may need to return error here indicating that the transaction cannot go through
        }
        public SystemResponse<string> CreatePersonalProtectiveEquipmentTransactions(ICollection<PersonalProtectiveEquipmentTransaction> personalProtectiveEquipmentTransactions)
        {
            //should add a validation business manager here
            var transactionTypes = GetTransactionTypes();

            foreach (var transaction in personalProtectiveEquipmentTransactions)
            {
                transaction.TransactionType = transactionTypes.Single(c => c.Id == transaction.TransactionTypeId);
            }

            //sort transactions so that incoming transactions will always be processed first

            List<int> preferences = new List<int> { IncomingTransactionDirectionId };

            IEnumerable<PersonalProtectiveEquipmentTransaction> orderedData = personalProtectiveEquipmentTransactions.OrderBy(item => preferences.IndexOf(item.TransactionType.TransactionDirectionId));

              //var personalProtectiveEquipmentTransactionsSorted = personalProtectiveEquipmentTransactions.OrderBy(c => c.TransactionType.TransactionDirectionId
              //      == IncomingTransactionDirectionId);

            SystemResponse<string> response = new SystemResponse<string>("No Error");

            foreach (var personalProtectiveEquipmentTransaction in orderedData)
            {

                var currentModelInventory = GetPersonalProtectiveEquipmentCategoryTypeModelInventory(personalProtectiveEquipmentTransaction.PersonalProtectiveEquipmentCategoryTypeModelId);

                //if its an outgoing transaction check the inventory levels
                //if the amount in current inventory exceeds an error must be returned

                //if transaction is outgoing check inventory levels first
                //check the direction of the transaction
                if (personalProtectiveEquipmentTransaction.TransactionType.TransactionDirectionId == TransactionDirectionOutgoingId)
                {
                    //make sure inventory being issued doesnt exceed existing quantity
                    if (currentModelInventory.Quantity < personalProtectiveEquipmentTransaction.Quantity)
                    {
                        response.ErrorMessages.Add("There aren't enough items in the inventory to meet that quantity.");
                        response.ErrorOccurred = true;
                    }
                    else
                    {
                        currentModelInventory.Quantity -= personalProtectiveEquipmentTransaction.Quantity;
                        currentModelInventory.PersonalProtectiveEquipmentCategoryTypeModel = null;
                        UpdatePersonalProtectiveEquipmentCategoryTypeModelInventory(currentModelInventory);
                        _dataManager.CreatePersonalProtectiveEquipmentTransaction(personalProtectiveEquipmentTransaction);
                    }
                }
                else if (personalProtectiveEquipmentTransaction.TransactionType.TransactionDirectionId == TransactionDirectionIncomingId)
                {
                    currentModelInventory.Quantity += personalProtectiveEquipmentTransaction.Quantity;
                    currentModelInventory.PersonalProtectiveEquipmentCategoryTypeModel = null;

                    UpdatePersonalProtectiveEquipmentCategoryTypeModelInventory(currentModelInventory);

                    _dataManager.CreatePersonalProtectiveEquipmentTransaction(personalProtectiveEquipmentTransaction);
                }
                else //neutral transaction
                {
                    _dataManager.CreatePersonalProtectiveEquipmentTransaction(personalProtectiveEquipmentTransaction);
                }
            }
            return response;
            //may need to return error here indicating that the transaction cannot go through
        }
        public SystemResponse<Dictionary<int, bool>> ValidateTransactionInventory(ICollection<PersonalProtectiveEquipmentTransaction> transactions)
        {
            var validationResult = new SystemResponse<Dictionary<int,bool>>(new Dictionary<int,bool>());

            //initialize a result for all transactions
            validationResult.result = transactions.ToDictionary(c => c.Id,c => true);

            //get the inventory by filtering out on the ids
            var transactionTypes = GetTransactionTypes();

            //current method gets all inventory
            var currentInventory = GetPersonalProtectiveEquipmentCategoryTypeModelInventorys();

            foreach (var transaction in transactions) { transaction.TransactionType = transactionTypes.Single(c => c.Id == transaction.TransactionTypeId); }

            //group all transactions by model id
            var transactionsGroupedByPPEModelId = transactions.GroupBy(c => c.PersonalProtectiveEquipmentCategoryTypeModelId);

            foreach (var transactionGrouping in transactionsGroupedByPPEModelId)
            {
                  int inventoryOfModel = currentInventory.Single(c => c.PersonalProtectiveEquipmentCategoryTypeModelId ==
                            transactionGrouping.First().PersonalProtectiveEquipmentCategoryTypeModelId).Quantity;

                //check if transactions are mixed incoming & outgoing
                if (transactionGrouping.Any(c => c.TransactionType.TransactionDirectionId == TransactionDirectionIncomingId) &&
                    transactionGrouping.Any(d => d.TransactionType.TransactionDirectionId == TransactionDirectionOutgoingId))
                {
                    var incomingTransactions = transactionGrouping.Where(c => c.TransactionType.TransactionDirectionId == TransactionDirectionIncomingId);

                    foreach (var incomingTransaction in incomingTransactions)
                    {
                        inventoryOfModel += incomingTransaction.Quantity;
                    }

                    var outgoingTransactions = transactionGrouping.Where(c => c.TransactionType.TransactionDirectionId == TransactionDirectionOutgoingId);

                    foreach (var outgoingTransaction in outgoingTransactions)
                    {
                        if (outgoingTransaction.Quantity <= inventoryOfModel)
                        {
                            inventoryOfModel -= outgoingTransaction.Quantity;
                        }
                        else
                        {
                            validationResult.result[outgoingTransaction.Id] = false;
                        }
                    }
                }
                else
                {
                    var outgoingTransactions = transactionGrouping.Where(c => c.TransactionType.TransactionDirectionId == TransactionDirectionOutgoingId);

                    foreach (var outgoingTransaction in outgoingTransactions)
                    {
                        if (outgoingTransaction.Quantity <= inventoryOfModel)
                        {
                            inventoryOfModel -= outgoingTransaction.Quantity;
                        }
                        else
                        {
                            validationResult.result[outgoingTransaction.Id] = false;
                        }
                    }
                }
            }
            return validationResult;
        }