コード例 #1
0
ファイル: ContactRepository.cs プロジェクト: AEJS1982/MyWorks
        public void Modify(Contact entity)
        {
            var auxContact = contacts.FirstOrDefault(x => x.id == entity.id);

            oc.Copy(entity, auxContact);
            this.SaveData(this.contacts);
        }
コード例 #2
0
        public ActionResult DeleteConfirmed(int id)
        {
            string resultTrans = "success";

            try
            {
                var DiagnosisList = diseaseRepository.GetDiagnosisByDiseaseId(id);
                if (DiagnosisList.Count() == 0)
                {
                    var     objSession = Session["user"] as MyClinic.Infrastructure.SessUser;
                    Disease Disease    = diseaseRepository.GetDiseaseById(id);
                    var     newDisease = ObjectCopier.Copy <Disease>(Disease);
                    newDisease.Status = 0;
                    diseaseRepository.UpdateFieldChangedOnly(Disease, newDisease);
                    /*For Add New Record to LogTable*/
                    logTran.UserId      = objSession.UserId;
                    logTran.ProcessType = "Delect Disease";
                    logTran.Description = "Delect Disease Name: " + Disease.Name;
                    logTran.LogDate     = DateTime.Now;
                    logRepository.Add(logTran);
                }
                else
                {
                    resultTrans = "failure";
                    return(Json(new { result = resultTrans, proccessType = "Delete", Id = id, strName = Translator.ThisDisease, strUsed = Translator.MsgDiagnosis }));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                resultTrans = "failure";
            }
            return(Json(new { result = resultTrans, proccessType = "Delete", Id = id }));
        }
コード例 #3
0
        public ActionResult DeleteConfirmed(int id)
        {
            User   originUser  = null;
            string resultTrans = "success";

            try
            {
                originUser = userRepository.GetUserById(id);
                var newUser = ObjectCopier.Copy <User>(originUser);

                newUser.IsActived = 2;//For Delete
                userRepository.UpdateFieldChangedOnly(originUser, newUser);

                /*For Add New Record to LogTable*/
                var objSession = Session["user"] as MyClinic.Infrastructure.SessUser;
                int userId     = objSession.UserId;

                logTran.UserId      = userId;
                logTran.ProcessType = "Delete User";
                logTran.Description = "Delete User Name :" + originUser.Name;
                logTran.LogDate     = DateTime.Now;
                logRepository.Add(logTran);
            }catch (Exception ex) {
                log.Error(ex);
                resultTrans = "failure";
            }
            return(Json(new { result = resultTrans, proccessType = "Delete", Id = id }));
        }
コード例 #4
0
        public ActionResult DeleteConfirmed(int id)
        {
            string resultTrans = "success";

            try
            {
                var prescriptionList = medicineRepository.GetPrescriptionByMedicineId(id);
                if (prescriptionList.Count() == 0)
                {
                    var      objSession = Session["user"] as MyClinic.Infrastructure.SessUser;
                    Medicine medicine   = medicineRepository.GetMedicineById(id);

                    var newMedicine = ObjectCopier.Copy <Medicine>(medicine);
                    newMedicine.Status = 0;

                    medicineRepository.UpdateFieldChangedOnly(medicine, newMedicine);
                    /*For Add New Record to LogTable*/
                    logTran.UserId      = objSession.UserId;
                    logTran.ProcessType = "Delect medicine";
                    logTran.Description = "Delect medicine Name: " + medicine.Name;
                    logTran.LogDate     = DateTime.Now;
                    logRepository.Add(logTran);
                }
                else
                {
                    resultTrans = "failure";
                    return(Json(new { result = resultTrans, proccessType = "Delete", Id = id, strName = Translator.ThisMedicine, strUsed = Translator.MsgPrescription }));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            return(Json(new { result = resultTrans, proccessType = "Delete", Id = id }));
        }
コード例 #5
0
        public void CopyEnum()
        {
            const CustomEnum customEnum = CustomEnum.Foo;
            object           copy       = ObjectCopier.Copy(customEnum, commandAssembly);

            Assert.AreNotSame(customEnum, copy);
            Assert.AreEqual(customEnum, copy);
        }
コード例 #6
0
        public void Should_be_able_to_copy_objects()
        {
            ObjectToCopy source = new ObjectToCopy
            {
                Id      = 10,
                Name    = "A dummy name",
                Address = "A dummy address"
            };

            ObjectToCopy destination = new ObjectToCopy();

            copier.Copy(source, destination);

            Assert.Equal(10, destination.Id);
            Assert.Equal("A dummy name", destination.Name);
            Assert.Equal("A dummy address", destination.Address);
        }
コード例 #7
0
        public void Copy()
        {
            var o    = new ObjectForObjectCopierTest(1, "foo");
            var copy = (ObjectForObjectCopierTest)ObjectCopier.Copy(o, commandAssembly);

            Assert.AreNotSame(o, copy);
            Assert.AreEqual(o.X, copy.X);
            Assert.AreEqual(o.Y, copy.Y);
        }
コード例 #8
0
        public void CopyPrimitives()
        {
            const string s    = "s";
            object       copy = ObjectCopier.Copy(s, commandAssembly);

            Assert.AreSame(s, copy);

            const int i = 1;

            copy = ObjectCopier.Copy(i, commandAssembly);
            Assert.AreNotSame(i, copy);
            Assert.AreEqual(i, copy);
        }
コード例 #9
0
        public void CopyExtraReverse()
        {
            CopyDestinationExtra s = new CopyDestinationExtra();

            FillSource(s);
            CopyBase d = new CopyBase();

            ObjectCopier.Copy(s, d);

            Assert.AreEqual(s.Id, d.Id);
            Assert.AreEqual(s.Email, d.Email);
            Assert.AreEqual(s.FirstName, d.FirstName);
            Assert.AreEqual(s.LastName, d.LastName);
            Assert.AreEqual(s.Phone, d.Phone);
        }
コード例 #10
0
        public void CopyToDictionary()
        {
            CopyBase s = new CopyBase();

            FillSource(s);
            Dictionary <string, object> d = new Dictionary <string, object>();

            ObjectCopier.Copy(s, d);

            Assert.Greater(d.Count, 0);

            Assert.AreEqual(s.Id, d["Id"]);
            Assert.AreEqual(s.Email, d["Email"]);
            Assert.AreEqual(s.FirstName, d["FirstName"]);
            Assert.AreEqual(s.LastName, d["LastName"]);
            Assert.AreEqual(s.Phone, d["Phone"]);
        }
コード例 #11
0
        public void CopyFromDictionary()
        {
            Dictionary <string, object> s = new Dictionary <string, object>();

            s.Add("Id", 1);
            s.Add("Email", "user@email");
            s.Add("FirstName", "test");
            s.Add("LastName", "user");
            s.Add("Phone", "800-555-1212");

            CopyBase d = new CopyBase();

            ObjectCopier.Copy(s, d);

            Assert.AreEqual(s["Id"], d.Id);
            Assert.AreEqual(s["Email"], d.Email);
            Assert.AreEqual(s["FirstName"], d.FirstName);
            Assert.AreEqual(s["LastName"], d.LastName);
            Assert.AreEqual(s["Phone"], d.Phone);
        }
コード例 #12
0
        public void CopyTypeChange()
        {
            CopyDestinationExtra s = new CopyDestinationExtra();

            FillSource(s);
            s.Address = "123 Street";
            s.City    = "Any City";
            s.State   = "NY";
            s.Zip     = "12345";

            CopyDestinationType d = new CopyDestinationType();

            ObjectCopier.Copy(s, d);

            Assert.AreEqual(s.Id, d.Id);
            Assert.AreEqual(s.Email, d.Email);
            Assert.AreEqual(s.FirstName, d.FirstName);
            Assert.AreEqual(s.LastName, d.LastName);
            Assert.AreEqual(s.Phone, d.Phone);
        }
コード例 #13
0
        public ActionResult DeleteConfirmed(int id)
        {
            string resultTrans = "success";

            try
            {
                var prescriptionList = diagnosisRepository.GetPrescriptionByDiagnosisId(id);
                if (prescriptionList.Count() == 0)
                {
                    DTODiagnosis dtodiagnosis = diagnosisRepository.GetDTODiagnosisById(id);

                    Diagnosis originDiagnosis = diagnosisRepository.GetDiagnosisById(id);
                    var       newDiagnosis    = ObjectCopier.Copy <Diagnosis>(originDiagnosis);

                    newDiagnosis.Status = 0;//For Delete
                    diagnosisRepository.UpdateFieldChangedOnly(originDiagnosis, newDiagnosis);

                    /*For Add New Record to LogTable*/
                    var objSession = Session["user"] as MyClinic.Infrastructure.SessUser;
                    int userId     = objSession.UserId;

                    logTran.UserId      = userId;
                    logTran.ProcessType = "Delete Diagnosis";
                    logTran.Description = "Delete Diagnosis, Patient Name :" + dtodiagnosis.Patient_Name;
                    logTran.LogDate     = DateTime.Now;
                    logRepository.Add(logTran);
                }
                else
                {
                    resultTrans = "failure";
                    return(Json(new { result = resultTrans, proccessType = "Delete", Id = id, strName = Translator.ThisDiagnosis, strUsed = Translator.MsgPrescription }));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                resultTrans = "failure";
            }
            return(Json(new { result = resultTrans, proccessType = "Delete", Id = id }));
        }
コード例 #14
0
ファイル: MainWindow.xaml.cs プロジェクト: minskowl/MY
        /// <summary>
        /// Handles the Executed event of the ExportCommand control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void ExportCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            e.Handled = true;
            var param = e.Parameter as ItemParams;

            if (param == null)
            {
                return;
            }
            switch (param.Type)
            {
            case ObjectType.Category:

                var dialog = new SaveFileDialog()
                {
                    Title           = "Create database file",
                    Filter          = LocalFileContext.FileFilter,
                    CreatePrompt    = false,
                    OverwritePrompt = true
                };

                if (!(dialog.ShowDialog(Application.Current.MainWindow) ?? false))
                {
                    return;
                }

                var destination = LocalFileContext.CreateDatabase(dialog.FileName);

                var copier = new ObjectCopier();

                copier.Copy(KbContext.CurrentKb, destination, param.IntId);
                MessageBox.Show("Export finished.", "Export");
                break;

            default:
                e.Handled = false;
                break;
            }
        }
コード例 #15
0
        public ActionResult DeleteConfirmed(int id)
        {
            string resultTrans = "success";

            try
            {
                var diagnosisList = employeeRepository.GetDiagnosisByEmployeeId(id);
                if (diagnosisList.Count() == 0)
                {
                    Employee originEmployee = employeeRepository.GetEmployeeById(id);
                    var      newEmployee    = ObjectCopier.Copy <Employee>(originEmployee);

                    newEmployee.Status = 0;//For Delete
                    employeeRepository.UpdateFieldChangedOnly(originEmployee, newEmployee);

                    /*For Add New Record to LogTable*/
                    var objSession = Session["user"] as MyClinic.Infrastructure.SessUser;
                    int userId     = objSession.UserId;

                    logTran.UserId      = userId;
                    logTran.ProcessType = "Delete Employee";
                    logTran.Description = "Delete Employee Name :" + originEmployee.Name;
                    logTran.LogDate     = DateTime.Now;
                    logRepository.Add(logTran);
                }
                else
                {
                    resultTrans = "failure";
                    return(Json(new { result = resultTrans, proccessType = "Delete", Id = id, strName = Translator.ThisEmployee, strUsed = Translator.MsgDiagnosis }));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                resultTrans = "failure";
            }
            return(Json(new { result = resultTrans, proccessType = "Delete", Id = id }));
        }
コード例 #16
0
 internal static LogLine Copy(LogLine other)
 {
     return(new LogLine(other.Raw, other.Index, other.LineType, other.TimeStamp, ObjectCopier.Copy(other.Data)));
 }
コード例 #17
0
 public void CopyArrayContainingArrayOfNonPrimitives()
 {
     ObjectCopier.Copy(new[] { new [] { CustomEnum.Foo } }, commandAssembly);
 }
コード例 #18
0
 public void CopyArrayContainingArray()
 {
     ObjectCopier.Copy(new[] { new [] { "a" } }, commandAssembly);
 }
コード例 #19
0
 public void CopyArray()
 {
     ObjectCopier.Copy(new[] { "a" }, commandAssembly);
 }
コード例 #20
0
        public IHttpActionResult InsertUpdateElement([FromBody] ElementExtended entity)
        {
            IList <ElementAttribute> selectedAttributes = null;
            IList <ElementCulture>   elementCulture     = new List <ElementCulture>();

            selectedAttributes = (from ea in entity.BasicAttributes
                                  where ea.Checked == true
                                  select new ElementAttribute
            {
                IDAttribute = ea.IDAttribute.Value,
                Value = ea.Value
            }).ToList();

            Element element = new Element();

            ObjectCopier.Copy(entity, element);

            //TODO: colocar validacao server-side e imagens
            elementCulture.Add(new ElementCulture()
            {
                Description = entity.Description,
                IDCulture   = entity.IDCulture,
                IDElement   = entity.IDElement.HasValue ? entity.IDElement.Value : 0,
                Name        = entity.Name
            });

            if (!element.IDElement.HasValue)
            {
                element.Status     = (short)Model.InfraStructure.Enums.StatusType.Active;
                element.IDCustomer = this.GetAuthCustomer().IDCustomer.Value;
                element.CreateDate = DateTime.Now;
                element.CreatedBy  = SiteContext.ActiveUserName;
                element.ModifyDate = DateTime.Now;
                element.ModifiedBy = SiteContext.ActiveUserName;
                ServiceContext.ElementService.Insert(element, elementCulture, selectedAttributes);

                return(Ok(new
                {
                    IDElement = element.IDElement,
                    IDCustomer = element.IDCustomer,
                    Message = Internationalization.Message.Element_Inserted_Successfully
                }));
            }
            else
            {
                if (CheckOwnership(element.IDCustomer))
                {
                    //entity.DefaultPicturePath = this.DefaultPicturePath(entity.IDCustomer, entity.IDElement.Value);
                    element.ModifyDate = DateTime.Now;
                    element.ModifiedBy = SiteContext.ActiveUserName;
                    ServiceContext.ElementService.Update(element, elementCulture, selectedAttributes);
                    return(Ok(new
                    {
                        IDElement = element.IDElement,
                        IDCustomer = element.IDCustomer,
                        Message = Internationalization.Message.Element_Updated_Successfully
                    }));
                }
                else
                {
                    return(BadRequest(Internationalization.Message.Element_Does_Not_Belongs_To_Customer));
                }
            }
        }
コード例 #21
0
        public async Task <IActionResult> Index()
        {
            //clear database
            ctx.Database.ExecuteSqlCommand("delete  from dbo.TestModels");
            //populate db
            var population = new List <Models.TestModel>();

            for (int i = 0; i < 10; i++)
            {
                var curr = new Models.TestModel
                {
                    FieldA = "FieldA_" + i,
                    FieldB = "FieldB_" + i,
                    FieldC = "FieldC_" + i,
                    FieldD = "FieldD_" + i,
                    FieldE = "FieldE_" + i,
                    FieldF = "FieldF_" + i
                };
                population.Add(curr);
                ctx.TestModels.Add(curr);
            }
            Expression <Func <Models.TestModel, bool> > test = m => (new int[] { 10, 3 }).Contains(m.Id);
            await ctx.SaveChangesAsync();

            //reset context...we are going into a different web page
            foreach (var item in population)
            {
                ctx.Entry(item).State = EntityState.Detached;
            }

            //
            //get data
            var original = await ctx.TestModels.Project().To <Models.TestViewModel>().ToArrayAsync();

            //

            //perform changes (this usually happens in user interface)...
            var copier  = new ObjectCopier <Models.TestViewModel, Models.TestViewModel>();
            var changed = original.Select(m => copier.Copy(m, new Models.TestViewModel())).ToList();

            changed[3].FieldD = "FieldD3_Changed";
            changed[5].FieldF = "FieldF%_Changed";
            changed.Remove(changed[7]);
            changed.Add(new Models.TestViewModel
            {
                FieldA = "FieldA_New",
                FieldB = "FieldB_Bew",
                FieldD = "FieldD_New",
                FieldE = "FieldE_New",
                FieldF = "FieldF_New"
            });
            //
            var repo =
                DefaultCRUDRepository.Create(ctx, ctx.TestModels, null, m => m.FieldA != "FieldA_0");

            DefaultCRUDRepository <ApplicationDbContext, Models.TestModel>
            .DeclareProjection <Models.ITestViewModel>(m => new Models.TestViewModel
            {
                FieldBC = m.FieldB + " " + m.FieldC
            });

            try
            {
                repo.Add <Models.ITestViewModel>(true, new Models.TestViewModel
                {
                    FieldA = "FieldA_ANew2",
                    FieldB = "FieldB_Bew2",
                    FieldD = "FieldD_New2",
                    FieldE = "FieldE_New",
                    FieldF = "FieldF_New"
                });
                repo.UpdateList <Models.ITestViewModel>(false, original, changed);
                changed[6].FieldA = "a change";
                changed[6].FieldF = "a F change";
                repo.Update <Models.ITestViewModel>(false, changed[6]);
                repo.Delete(changed[8].Id);
                await repo.SaveChanges();
            }
            catch (Exception ex)
            {
                var exc = ex;
            }
            //
            //Retrieve changed data and perform custo processing on ViewModel Projection
            var finalData = await repo.GetPage <Models.TestViewModel>(null,
                                                                      x => x.OrderBy(m => m.FieldA),
                                                                      1, 5);

            var finalData1 = await repo.GetPage <Models.TestViewModel>(null,
                                                                       x => x.OrderBy(m => m.FieldA),
                                                                       2, 5);

            var detail = await repo.GetById <Models.ITestViewModel, int>(original[1].Id.Value);

            return(View());
        }
コード例 #22
0
ファイル: Aggregate.cs プロジェクト: rakyury/infrastructure
 /// <summary>
 /// Creates a deep-copy of the current aggregate object graph by traversing all public and non-public fields.
 /// </summary>
 /// <remarks>Aggregate object graph must be non-recursive.</remarks>
 protected internal virtual Aggregate Copy()
 {
     return(ObjectCopier.Copy(this));
 }
コード例 #23
0
 /// <summary>
 /// Creates a deep-copy of the current saga object graph by traversing all public and non-public fields.
 /// </summary>
 /// <remarks>Aggregate object graph must be non-recursive.</remarks>
 protected internal virtual Saga Copy()
 {
     return(ObjectCopier.Copy(this));
 }
コード例 #24
0
        public ActionResult EditUserProfile(MyClinic.Infrastructure.UserEdit userEdit)
        {
            bool       checkError = true;
            UserModels viewModel  = null;
            var        objSession = Session["user"] as MyClinic.Infrastructure.SessUser;

            if (objSession == null)
            {
                return(HttpNotFound());
            }
            else
            {
                userEdit.Id = objSession.UserId;
            }
            User user      = userRepository.GetUserById(userEdit.Id);
            User checkUser = userRepository.GetUserByUsername(userEdit.UserName);

            try
            {
                if (String.IsNullOrEmpty(checkUser.UserName) == false)
                {
                    if (user.UserName != userEdit.UserName)
                    {
                        ModelState.AddModelError("UserName", "UserName Exist");
                    }
                }

                if (String.IsNullOrEmpty(userEdit.ConfirmPassword))
                {
                    userEdit.ConfirmPassword = String.Empty;
                }

                if (String.IsNullOrEmpty(userEdit.Password))
                {
                    userEdit.Password = String.Empty;
                }

                if (userEdit.ConfirmPassword.Trim() != userEdit.Password.Trim())
                {
                    ModelState.AddModelError("ConfirmPassword", "Confirm Password is not match.");
                }

                if (ModelState.IsValid)
                {
                    User oldUser       = userRepository.GetUserById(userEdit.Id);
                    var  newUser       = ObjectCopier.Copy <User>(oldUser);
                    var  savePathImage = Server.MapPath("~/Uploads/User/") + user.Id;
                    ImageHelper.SaveImage(savePathImage, user.Id + ".jpg", userEdit.ImageStream);
                    if (String.IsNullOrEmpty(userEdit.Password) == false)
                    {
                        newUser.Password = Common.EncryptString(userEdit.Password);
                    }
                    newUser.Name         = userEdit.Name;
                    newUser.UserName     = userEdit.UserName;
                    newUser.Email        = userEdit.Email;
                    newUser.Name         = userEdit.Name;
                    newUser.ModifiedBy   = objSession.UserId;
                    newUser.ModifiedDate = DateTime.Now;
                    string diffString = oldUser.EnumeratePropertyDifferencesInString(newUser);
                    objSession.Password = newUser.Password;
                    userRepository.UpdateFieldChangedOnly(oldUser, newUser);
                    /*For Add New Record to LogTable*/
                    int userId = objSession.UserId;
                    logTran.UserId      = userId;
                    logTran.ProcessType = "Update Profile";
                    logTran.Description = "Update Profile User " + user.Name + " value as follow: " + diffString;
                    logTran.LogDate     = DateTime.Now;
                    logRepository.Add(logTran);
                    checkError = false;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                ModelState.AddModelError(string.Empty, Translator.UnexpectedError);
            }

            if (checkError == true)
            {
                viewModel = new UserModels
                {
                    user       = user,
                    userEdit   = userEdit,
                    checkError = checkError,
                    checkPost  = true
                };
                return(View(viewModel));
            }
            else
            {
                return(RedirectToAction("Index", "Home"));
            }
        }
コード例 #25
0
        /// <summary>
        /// Determines whether node is accessible to user.
        /// </summary>
        /// <param name="controllerTypeResolver">The controller type resolver.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="context">The context.</param>
        /// <param name="node">The node.</param>
        /// <returns>
        ///     <c>true</c> if accessible to user; otherwise, <c>false</c>.
        /// </returns>
        public bool IsAccessibleToUser(IControllerTypeResolver controllerTypeResolver, DefaultSiteMapProvider provider, HttpContext context, SiteMapNode node)
        {
            // Is security trimming enabled?
            if (!provider.SecurityTrimmingEnabled)
            {
                return(true);
            }

            // Is it an external node?
            var nodeUrl = node.Url;

            if (nodeUrl.StartsWith("http") || nodeUrl.StartsWith("ftp"))
            {
                return(true);
            }

            // Is it a regular node?
            var mvcNode = node as MvcSiteMapNode;

            if (mvcNode == null)
            {
                throw new AclModuleNotSupportedException(
                          Resources.Messages.AclModuleDoesNotSupportRegularSiteMapNodes);
            }

            // Clickable? Always accessible.
            if (mvcNode.Clickable == false)
            {
                return(true);
            }

            // Time to delve into the AuthorizeAttribute defined on the node.
            // Let's start by getting all metadata for the controller...
            var controllerType = controllerTypeResolver.ResolveControllerType(mvcNode.Area, mvcNode.Controller);

            if (controllerType == null)
            {
                return(false);
            }

            // Find routes for the sitemap node's url
            HttpContextBase httpContext    = new HttpContextWrapper(context);
            string          originalPath   = httpContext.Request.Path;
            var             originalRoutes = RouteTable.Routes.GetRouteData(httpContext);

            httpContext.RewritePath(nodeUrl, true);

            HttpContextBase httpContext2 = new HttpContext2(context);
            RouteData       routes       = mvcNode.GetRouteData(httpContext2);

            if (routes == null)
            {
                return(true); // Static URL's will have no route data, therefore return true.
            }
            foreach (var routeValue in mvcNode.RouteValues)
            {
                routes.Values[routeValue.Key] = routeValue.Value;
            }
            if (!routes.Route.Equals(originalRoutes.Route) || originalPath != nodeUrl || mvcNode.Area == String.Empty)
            {
                routes.DataTokens.Remove("area");
                //routes.DataTokens.Remove("Namespaces");
                //routes.Values.Remove("area");
            }
            var requestContext = new RequestContext(httpContext, routes);

            // Create controller context
            var controllerContext = new ControllerContext();

            controllerContext.RequestContext = requestContext;

            // Whether controller is built by the ControllerFactory (or otherwise by Activator)
            bool factoryBuiltController = false;

            try
            {
                string controllerName = requestContext.RouteData.GetRequiredString("controller");
                controllerContext.Controller = ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, controllerName) as ControllerBase;
                factoryBuiltController       = true;
            }
            catch
            {
                try
                {
                    controllerContext.Controller = Activator.CreateInstance(controllerType) as ControllerBase;
                }
                catch
                {
                }
            }

            ControllerDescriptor controllerDescriptor = null;

            if (typeof(IController).IsAssignableFrom(controllerType))
            {
                controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
            }
            else if (typeof(IAsyncController).IsAssignableFrom(controllerType))
            {
                controllerDescriptor = new ReflectedAsyncControllerDescriptor(controllerType);
            }

            ActionDescriptor actionDescriptor = null;

            try
            {
                actionDescriptor = controllerDescriptor.FindAction(controllerContext, mvcNode.Action);
            }
            catch
            {
            }
            if (actionDescriptor == null)
            {
                actionDescriptor = controllerDescriptor.GetCanonicalActions().Where(a => a.ActionName == mvcNode.Action).FirstOrDefault();
            }

            // Verify security
            try
            {
                if (actionDescriptor != null)
                {
#if NET35
                    IEnumerable <AuthorizeAttribute> authorizeAttributesToCheck =
                        actionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).OfType
                        <AuthorizeAttribute>().ToList()
                        .Union(
                            controllerDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).OfType
                            <AuthorizeAttribute>().ToList());
#else
                    IFilterProvider      filterProvider = ResolveFilterProvider();
                    IEnumerable <Filter> filters;

                    // If depencency resolver has an IFilterProvider registered, use it
                    if (filterProvider != null)
                    {
                        filters = filterProvider.GetFilters(controllerContext, actionDescriptor);
                    }
                    // Otherwise use FilterProviders.Providers
                    else
                    {
                        filters = FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor);
                    }

                    IEnumerable <AuthorizeAttribute> authorizeAttributesToCheck =
                        filters
                        .Where(f => typeof(AuthorizeAttribute).IsAssignableFrom(f.Instance.GetType()))
                        .Select(f => f.Instance as AuthorizeAttribute);
#endif

                    // Verify all attributes
                    foreach (var authorizeAttribute in authorizeAttributesToCheck)
                    {
                        try
                        {
                            var currentAuthorizationAttributeType = authorizeAttribute.GetType();

                            var builder             = new AuthorizeAttributeBuilder();
                            var subclassedAttribute =
                                currentAuthorizationAttributeType == typeof(AuthorizeAttribute) ?
                                new InternalAuthorize(authorizeAttribute) :    // No need to use Reflection.Emit when ASP.NET MVC built-in attribute is used
                                (IAuthorizeAttribute)builder.Build(currentAuthorizationAttributeType).Invoke(null);

                            // Copy all properties
                            ObjectCopier.Copy(authorizeAttribute, subclassedAttribute);

                            if (!subclassedAttribute.IsAuthorized(controllerContext.HttpContext))
                            {
                                return(false);
                            }
                        }
                        catch
                        {
                            // do not allow on exception
                            return(false);
                        }
                    }
                }

                // No objection.
                return(true);
            }
            finally
            {
                // Restore HttpContext
                httpContext.RewritePath(originalPath, true);

                // Release controller
                if (factoryBuiltController)
                {
                    ControllerBuilder.Current.GetControllerFactory().ReleaseController(controllerContext.Controller);
                }
            }
        }
コード例 #26
0
        public void CannotCopyNoArgConstructorClasses()
        {
            var o = new ObjectWithoutNoArgConstructor("foo");

            ObjectCopier.Copy(o, commandAssembly);
        }