public ActionResponse Authenticate(string username, string password)
        {
            ActionResponse response = new ActionResponse();

            try
            {
                var context = DbContextFactory.GetDbContext();
                bool hasAny = context.Users.Any(u => u.Username == username && u.Password == password);

                if (hasAny)
                {
                    response.IsSuccess = true;
                }
                else
                {
                    response.Error = ErrorFactory.InvalidUsernameOrPassword;
                }
            }
            catch (Exception exc)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(exc);
                response.Error = ErrorFactory.ConnectingToDatabaseFailure;
            }

            return response;
        }
        public ActionResponse Edit(TestW testW)
        {
            var response = new ActionResponse();

            var test = db.Tests.Single(c => c.Id == testW.Id);
            test.Name = testW.Name;
            test.TestCategoryId = testW.TestCategoryId;
            test.AcredetationLevelId = testW.AcredetationLevelId;
            test.Temperature = testW.Temperature;
            test.UnitName = testW.UnitName;
            test.TypeId = testW.TypeId;
            test.MethodValue = testW.MethodValue;
            //test.TestMethods = testW.TestMethods;

            try
            {
                var toDelete = new List<TestMethod>();
                //1 add all to be deleted that not existing in the new list
                foreach (var item in test.TestMethods)
                {
                    if (!testW.TestMethods.Any(m => m.Method == item.Method))
                    {
                        toDelete.Add(item);
                        //test.TestMethods.Remove(item);
                        //db.TestMethods.Remove(item);
                    }
                }

                //1.5 Remove them
                foreach (var item in toDelete)
                {
                    db.TestMethods.Remove(item);
                }

                //2 now insert all that are new for the list
                foreach (var item in testW.TestMethods)
                {
                    if (!test.TestMethods.Any(m => m.Method == item.Method))
                    {
                        var method = new TestMethod();
                        method.Id = Guid.NewGuid();
                        method.Method = item.Method;

                        test.TestMethods.Add(method);
                    }
                }

                response.IsSuccess = true;
                db.SaveChanges();
            }
            catch (Exception exc)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(exc);
                response.IsSuccess = false;
                response.Error = ErrorFactory.MethodInUseError;
            }

            return response;
        }
        public ActionResponse ArchiveDiary(Guid diaryId)
        {
            var res = new ActionResponse();

            try
            {
                var diary = db.Diaries.Single(d => d.Id == diaryId);

                ArchivedDiary archivedDiary = new ArchivedDiary();

                archivedDiary.Id = Guid.NewGuid();
                archivedDiary.Number = diary.Number;
                archivedDiary.AcceptanceDateAndTime = diary.AcceptanceDateAndTime;
                archivedDiary.LetterNumber = diary.LetterNumber != null ? diary.LetterNumber.ToString() : "";
                archivedDiary.LetterDate = diary.LetterDate;
                archivedDiary.Contractor = diary.Contractor;
                archivedDiary.Client = diary.Client.Name;
                archivedDiary.ClientMobile = diary.Client.Mobile;
                archivedDiary.Comment = diary.Comment;
                var request = diary.Requests.First();
                archivedDiary.RequestDate = request.Date;
                archivedDiary.RequestAcceptedBy = request.User.FirstName.Substring(0,1) + ". " + request.User.LastName;
                archivedDiary.RequestTestingPeriod = request.TestingPeriod;
                archivedDiary.Remark = new DiaryW(diary).Remark;
                var protocol = request.Protocols.First();
                archivedDiary.ProtocolIssuedDate = protocol.IssuedDate;
                archivedDiary.ProtocolTesterMKB = protocol.TesterMKB;
                archivedDiary.ProtocolTesterFZH = protocol.TesterFZH;
                archivedDiary.ProtocolLabLeader = protocol.LabLeader;

                foreach (var remark in protocol.ProtocolsRemarks)
                {
                    ArchivedProtocolRemark aremark = new ArchivedProtocolRemark();
                    aremark.Id = Guid.NewGuid();
                    aremark.ArchivedDiaryId = archivedDiary.Id;
                    aremark.Remark = remark.Remark.Text;
                    aremark.AcredetationLevel = remark.AcredetationLevel.Level;
                    aremark.Number = remark.Number;

                    db.ArchivedProtocolRemarks.Add(aremark);
                }
                db.ProtocolsRemarks.RemoveRange(protocol.ProtocolsRemarks);

                var products = diary.Products;
                foreach (var product in products)
                {
                    ArchivedProduct aproduct = new ArchivedProduct();

                    aproduct.Id = Guid.NewGuid();
                    aproduct.Name = product.Name;
                    aproduct.Number = product.Number;
                    aproduct.Quantity = product.Quantity;

                    var productTests = product.ProductTests;
                    foreach (var ptest in productTests)
                    {
                        ArchivedProductTest aptest = new ArchivedProductTest();

                        aptest.Id = Guid.NewGuid();
                        aptest.TestName = ptest.Test.Name;
                        aptest.TestUnitName = ptest.Test.UnitName;
                        aptest.TestMethods = ptest.TestMethod.Method;
                        aptest.TestAcredetationLevel = ptest.Test.AcredetationLevel.Level;
                        aptest.TestTemperature = ptest.Test.Temperature;
                        aptest.TestCategory = ptest.Test.TestCategory.Name;
                        aptest.TestType = ptest.Test.TestType.Type;
                        aptest.TestTypeShortName = ptest.Test.TestType.ShortName;
                        aptest.MethodValue = ptest.MethodValue;
                        aptest.Remark = ptest.Remark;

                        //aptest.Units = ptest.Units;

                        var protocolResults = ptest.ProtocolResults;
                        foreach (var presult in protocolResults)
                        {
                            ArchivedProtocolResult apresult = new ArchivedProtocolResult();

                            apresult.Id = Guid.NewGuid();
                            apresult.Results = presult.Results;
                            //apresult.MethodValue = presult.MethodValue;
                            apresult.ResultNumber = presult.ResultNumber;
                            apresult.ArchivedDiaryId = archivedDiary.Id;

                            aptest.ArchivedProtocolResults.Add(apresult);
                        }

                        db.ProtocolResults.RemoveRange(ptest.ProtocolResults);
                        aproduct.ArchivedProductTests.Add(aptest);
                    }

                    db.ProductTests.RemoveRange(product.ProductTests);
                    archivedDiary.ArchivedProducts.Add(aproduct);
                }

                db.Products.RemoveRange(diary.Products);
                db.ArchivedDiaries.Add(archivedDiary);

                db.Protocols.RemoveRange(request.Protocols);
                db.Requests.Remove(request);

                db.Diaries.Remove(diary);

                db.SaveChanges();

                res.IsSuccess = true;
                res.ResponseObject = archivedDiary.Id;
                res.SuccessMsg = "Архивирането на дневник: " + diary.Number + " премина успешно.";
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }
            catch (Exception exc)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(exc);
                res.Error = ErrorFactory.UnableToArchiveDiary;
            }

            return res;
        }
        public ActionResponse RegenerateArchivedProtocol(ArchivedDiaryW adiary)
        {
            var response = new ActionResponse();

            try
            {
                var filesRep = new FilesRepository();
                filesRep.RegenerateProtocolReport(adiary);

                response.IsSuccess = true;
                response.SuccessMsg = "Успешно опресняване на архивирания протокол!";
            }
            catch (Exception exc)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(exc);
                response.Error = ErrorFactory.UnableToRefreshArchivedProtocol;
            }

            return response;
        }