Esempio n. 1
0
 public override void AddContextData(IContext context)
 {
     base.AddContextData(context);
     context.Add(this);
     context.Add(_info);
     context.Add(View.Value);
 }
Esempio n. 2
0
        public Guid Add(string ci_cd_workflow_id, string job_num, string stage)
        {
            try
            {
                Guid workflow_id = _workflow.Where(w => w.CICDWorkflowId.Equals(ci_cd_workflow_id))
                                   .Select(w => w.Id).FirstOrDefault();
                if (workflow_id.Equals(Guid.Empty))
                {
                    throw NotFound();
                }

                StageEnum stage_code          = GetStageCode(stage);
                int       number_of_jobs_done = _pipeline.Count(p => p.WorkflowId.Equals(workflow_id));
                Pipeline  pipeline            = _pipeline.Add(new Pipeline
                {
                    CICDJobNum = job_num,
                    Stage      = stage_code,
                    WorkflowId = workflow_id,
                    CustomName = stage_code.Equals(StageEnum.Custom) ? stage : null,
                    Step       = number_of_jobs_done + 1
                });
                SaveChanges();
                return(pipeline.Id);
            }
            catch (Exception e)
            {
                throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred while add a pipeline!",
                                                                         e, DateTime.Now, "Server", "Service_Pipeline_Add");
            }
        }
Esempio n. 3
0
        public ReporteDocumentosIngresadosRequest EjecutarGeneraReporteDocumentosIngresados(ReporteDocumentosIngresadosRequest request)
        {
            var correlativo = _context.Query <Modelo.dat_reporte_digitalizado>().Select(x => x.numero_reporte).DefaultIfEmpty(0).Max() + 1;

            var reporte = new Modelo.dat_reporte_digitalizado
            {
                estado                      = 1,
                numero_reporte              = correlativo,
                user_registro               = request.user,
                ip_user_registro            = request.ip,
                fecha_registro              = DateTime.Now,
                codigo_trabajador_entregado = request.codigo_trabajador_entrega,
                coddep_entregado            = request.codigo_dependencia_entrega,
                codigo_trabajador_recibido  = request.codigo_trabajador_recibido,
                coddep_recibido             = request.codigo_dependencia_recibido,
                observacion                 = request.observaciones,
                user_audit                  = request.user,
                ip_audit                    = request.ip,
                fecha_recibido              = DateTime.Now,
                fecha_audit                 = DateTime.Now,
                fecha_filtro_ini            = null,
                fecha_filtro_fin            = null
            };

            _context.Add(reporte);
            _uow.Save();

            request.id_reporte  = reporte.id_reporte;
            request.correlativo = correlativo.Value;

            return(request);
        }
Esempio n. 4
0
        // Use this for initialization
        private void Start()
        {
            _context = new EntityObject();
            _context.Add(_conquerGameField);
            _context.Add(_gameCamera);

            DontDestroyOnLoad(gameObject);
            StartGameBehaviour();
        }
Esempio n. 5
0
        public async Task <ActionResult <TodoListView> > CreateList([FromBody] ListCreate list)
        {
            var createdList = new TodoList()
            {
                Name  = list.Name,
                Owner = AuthorizedUser,
            };

            db.Add(createdList);
            await db.SaveChangesAsync();

            return(Created($"/api/lists/{createdList.Id}", new TodoListView(createdList)));
        }
        public override void Render(HttpContextBase httpContext, IContext requestContext)
        {
            if (httpContext.Session != null)
                foreach (object key in httpContext.Session.Keys)
                {
                    if (requestContext.Contains(key))
                        throw new ApplicationException(String.Format("{0} is present on both the Session and the Request.", key));

                    requestContext.Add(key.ToString(), httpContext.Session[key.ToString()]);
                }

            try
            {
                var templateTuple = manager.RenderTemplate(requestContext.Response.RenderTarget, (IDictionary<string, object>)requestContext);
                manager = templateTuple.Item1;
                TextReader reader = templateTuple.Item2;
                char[] buffer = new char[4096];
                int count = 0;
                while ((count = reader.ReadBlock(buffer, 0, 4096)) > 0)
                    httpContext.Response.Write(buffer, 0, count);
            }
            catch (Exception ex)
            {
                httpContext.Response.StatusCode = 500;
                httpContext.Response.Write(RenderException(requestContext.Response.RenderTarget, ex, true));
            }
        }
        public dynamic AddExecutor(Guid tool_id, ExecutorCreateM model)
        {
            try
            {
                EnsureToolExisted(tool_id);

                Executor executor = _executor.Add(new Executor
                {
                    Language = model.Language,
                    ToolId   = tool_id,
                    Name     = model.Name
                });
                SaveChanges();

                return(new
                {
                    executor.Id,
                    executor.Name,
                    executor.Language
                });
            }
            catch (Exception e)
            {
                throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred!",
                                                                         e, DateTime.Now, "Server", "Service-Configuration-AddExecutor");
            }
        }
Esempio n. 8
0
        public override void Render(HttpContextBase httpContext, IContext requestContext)
        {
            if (httpContext.Session != null)
            {
                foreach (object key in httpContext.Session.Keys)
                {
                    if (requestContext.Contains(key))
                    {
                        throw new ApplicationException(String.Format("{0} is present on both the Session and the Request.", key));
                    }

                    requestContext.Add(key.ToString(), httpContext.Session[key.ToString()]);
                }
            }

            try
            {
                var templateTuple = manager.RenderTemplate(requestContext.Response.RenderTarget, (IDictionary <string, object>)requestContext);
                manager = templateTuple.Item1;
                TextReader reader = templateTuple.Item2;
                char[]     buffer = new char[4096];
                int        count  = 0;
                while ((count = reader.ReadBlock(buffer, 0, 4096)) > 0)
                {
                    httpContext.Response.Write(buffer, 0, count);
                }
            }
            catch (Exception ex)
            {
                httpContext.Response.Write(RenderException(requestContext.Response.RenderTarget, ex, true));
            }
        }
Esempio n. 9
0
        public ProjectFrameworkM AddMany(Guid project_id, IList <Guid> framework_ids)
        {
            try
            {
                foreach (var framework_id in framework_ids)
                {
                    if (!_framework.Any(f => f.Id.Equals(framework_id)))
                    {
                        throw NotFound(framework_id, "framework id");
                    }
                }
                foreach (var framework_id in framework_ids)
                {
                    if (!_projectFramework.Any(pf => pf.ProjectId.Equals(project_id) && pf.FrameworkId.Equals(framework_id)))
                    {
                        _projectFramework.Add(new ProjectFramework
                        {
                            ProjectId   = project_id,
                            FrameworkId = framework_id
                        });
                    }
                }
                SaveChanges();

                return(GetDetail(project_id));
            }
            catch (Exception e)
            {
                throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred while add project frameworks!",
                                                                         e, DateTime.Now, "Server", "Service_ProjectFramework_AddMany");
            }
        }
Esempio n. 10
0
        public LanguageM Add(LanguageCreateM model)
        {
            try
            {
                if (!("Server".Equals(model.Side) || "Client".Equals(model.Side) || "Database".Equals(model.Side)))
                {
                    throw BadRequest("Side value of framework must be 'Server', 'Client' or 'Database'!");
                }
                if (_language.Any(l => l.Name.Equals(model.Name) && l.Side.Equals(model.Side)))
                {
                    throw BadRequest("This language is existed!");
                }

                var language = _language.Add(new Language
                {
                    Name = model.Name,
                    Side = model.Side
                });
                SaveChanges();
                return(new LanguageM
                {
                    Id = language.Id,
                    Name = language.Name,
                    Side = language.Side
                });
            }
            catch (Exception e)
            {
                throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred while add a language!",
                                                                         e, DateTime.Now, "Server", "Service_Language_Add");
            }
        }
        public dynamic AddExecutorImage(Guid tool_id, Guid executor_id, ExecutorImageCreateM model)
        {
            try
            {
                EnsureExecutorExisted(tool_id, executor_id);

                ExecutorImage executor_image = _executorImage.Add(new ExecutorImage
                {
                    ExecutorId = executor_id,
                    Name       = model.Name,
                    Value      = model.Value
                });
                SaveChanges();

                return(new
                {
                    executor_image.Id,
                    executor_image.Name,
                    executor_image.Value
                });
            }
            catch (Exception e)
            {
                throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred!",
                                                                         e, DateTime.Now, "Server", "Service-Configuration-AddExecutorImage");
            }
        }
        public dynamic AddResourceClass(Guid tool_id, Guid executor_id, ResourceClassCreateM model)
        {
            try
            {
                EnsureExecutorExisted(tool_id, executor_id);

                ResourceClass resource_class = _resourceClass.Add(new ResourceClass
                {
                    ExecutorId = executor_id,
                    Name       = model.Name
                });
                SaveChanges();

                return(new
                {
                    resource_class.Id,
                    resource_class.Name
                });
            }
            catch (Exception e)
            {
                throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred!",
                                                                         e, DateTime.Now, "Server", "Service-Configuration-AddResourceClass");
            }
        }
Esempio n. 13
0
        public Guid Add(GHAuthenticatedUserInfo model, Guid vsc_id, out bool is_connected)
        {
            try
            {
                Account account = _account.GetOne(a => a.ThirdPartyAccountId.Trim().Equals(model.User.Id.ToString().Trim()));
                if (account == null)
                {
                    account = _account.Add(new Account
                    {
                        Name = model.User.Login,
                        ThirdPartyAccountId = model.User.Id.ToString(),
                        IsMain = false,
                        ToolId = ToolID.Github
                    });
                }
                account.AccessToken = model.Token.Access_token;
                account.AvatarUrl   = model.User.Avatar_url;
                account.Email       = model.Email;
                SaveChanges();

                is_connected = account.UserId != null;
                return(account.Id);
            }
            catch (Exception e)
            {
                throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred while add third party account!",
                                                                         e, DateTime.Now, "Server", "Service_Account_Add");
            }
        }
        public dynamic AddStep(Guid tool_id, Guid executor_id, StepCreateM model)
        {
            try
            {
                EnsureExecutorExisted(tool_id, executor_id);

                Step step = _step.Add(new Step
                {
                    ExecutorId   = executor_id,
                    ReplacedText = model.ReplacedText,
                    Stage        = model.Stage,
                    Name         = model.Name,
                    Text         = model.Text
                });
                SaveChanges();

                return(new
                {
                    step.Id,
                    step.Name,
                    step.ReplacedText,
                    step.Stage,
                    step.Text
                });
            }
            catch (Exception e)
            {
                throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred!",
                                                                         e, DateTime.Now, "Server", "Service-Configuration-AddStep");
            }
        }
Esempio n. 15
0
        protected override StatusResponse Registrar(MovimientoDocumentoRequest request)
        {
            var sr = new StatusResponse {
                Value = 0
            };

            _context.Query <Modelo.movimiento_documento>()
            .Where(x => x.ID_DOCUMENTO == request.id_documento &&
                   x.ID_DEPENDENCIA_DESTINO == request.id_dependencia_destino &&
                   x.derivado == 0)
            .ToList().ForEach(mov => { mov.derivado = 1; });

            var movimiento_documento = new Modelo.movimiento_documento
            {
                ID_DOCUMENTO           = request.id_documento,
                ID_OFICIO              = request.id_oficio,
                ID_DEPENDENCIA_ORIGEN  = request.id_dependencia_origen,
                ID_DEPENDENCIA_DESTINO = request.id_dependencia_destino,
                AUDIT_MOD              = DateTime.Now,
                enviado    = request.enviado,
                derivado   = request.derivado,
                finalizado = request.finalizado
            };

            _context.Add(movimiento_documento);
            _uow.Save();

            return(sr);
        }
Esempio n. 16
0
        public string EjecutarRegistrarExterno(int year, string username, string hostname)
        {
            var contador = new Modelo.contador
            {
                AUDITMOD = DateTime.Now,
                hostname = hostname,
                usuario  = username,
                cont     = _context.Query <Modelo.contador>().Max(x => x.cont) + 1
            };

            //System.Environment.MachineName;
            _context.Add(contador);
            _uow.Save();
            var numero = $"{contador.cont}".PadLeft(8, '0');

            return($"{numero}-{year}");
        }
Esempio n. 17
0
 public void Add(Guid repository_id, string branch_name, string sha)
 {
     try
     {
         _branch.Add(new Branch
         {
             Sha          = sha,
             IsDefault    = false,
             Name         = branch_name,
             RepositoryId = repository_id
         });
         SaveChanges();
     }
     catch (Exception e)
     {
         throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred while add a branch!",
                                                                  e, DateTime.Now, "Server", "Service_Branch_Add");
     }
 }
Esempio n. 18
0
        public IResult <T> Create(T person)
        {
            var result = new Result <T>();

            Context.Add(person);
            var totalRecordsSaved = Context.SaveChanges();

            result.HasErrors = totalRecordsSaved <= 0;
            return(result);
        }
Esempio n. 19
0
        public void SetupTechnology(ProjectTechnologySetupM model, Guid project_id)
        {
            try
            {
                var repository = _repository.Where(r => r.Id.Equals(model.RepositoryId))
                                 .Select(r => new {
                    r.HookId
                }).FirstOrDefault();
                if (repository == null)
                {
                    throw NotFound(model.RepositoryId, "repository id");
                }
                if (repository.HookId == null)
                {
                    throw BadRequest("Must follow repository first!");
                }

                Project project = _project.GetOne(project_id);
                if (project == null)
                {
                    throw NotFound(project_id, "project id");
                }

                if (model.ToolIds != null)
                {
                    foreach (var tool_id in model.ToolIds)
                    {
                        IList <Tool> tools = _tool.GetAll();
                        if (!tools.Any(t => t.Id.Equals(tool_id)))
                        {
                            throw NotFound(tool_id, "tool id");
                        }
                    }
                }

                if (model.ToolIds != null)
                {
                    foreach (var tool_id in model.ToolIds)
                    {
                        _projectTool.Add(new ProjectTool
                        {
                            ProjectId = project_id,
                            ToolId    = tool_id
                        });
                    }
                }

                SaveChanges();
            }
            catch (Exception e)
            {
                throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred while set up techology for project!",
                                                                         e, DateTime.Now, "Server", "Service_Project_SetupTechnology");
            }
        }
Esempio n. 20
0
        public async Task <TModel> Add(TModel model)
        {
            var entity = _context.Add(_mapper.Map <TEntity>(model));
            await _context.SaveAsync();

            var result = _mapper.Map <TModel>(entity);

            await PostAddAsync(result);

            return(result);
        }
Esempio n. 21
0
        public IResult <T> Create(T obj)
        {
            var result = new Result <T>();

            Context.Add(obj);
            var totalRecordsSaved = Context.SaveChanges();

            result.HasErrors    = totalRecordsSaved <= 0;
            result.ResultObject = obj;
            return(result);
        }
Esempio n. 22
0
 public void AssignProjectManager(Guid user_id, Guid project_id)
 {
     try
     {
         Permission permission = _permission.GetOne(p => p.ProjectId.Equals(project_id) && p.RoleId.Equals(RoleID.Project_Manager));
         if (permission == null)
         {
             _permission.Add(new Permission
             {
                 RoleId    = RoleID.Project_Manager,
                 ProjectId = project_id,
                 UserId    = user_id
             });
         }
         else
         {
             if (!permission.UserId.Equals(user_id))
             {
                 _permission.Remove(permission);
                 _permission.Add(new Permission
                 {
                     RoleId    = RoleID.Project_Manager,
                     ProjectId = project_id,
                     UserId    = user_id
                 });
             }
             else
             {
                 throw BadRequest("The user has already been project manager!");
             }
         }
         SaveChanges();
     }
     catch (Exception e)
     {
         throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred while assign project manager!",
                                                                  e, DateTime.Now, "Server", "Service_Permission_AssignProjectManager");
     }
 }
Esempio n. 23
0
        public SprintTasksM AddMany(Guid project_id, Guid sprint_id, TaskSprintCreateM model)
        {
            try
            {
                foreach (var side in model.Sides)
                {
                    if (!("Server".Equals(side.Side) || "Client".Equals(side.Side) || "Database".Equals(side.Side)))
                    {
                        throw BadRequest("Side value must be 'Server', 'Client' or 'Database'!");
                    }
                    if (side.Tasks.Count == 0)
                    {
                        throw BadRequest("No task is assigned!");
                    }
                    foreach (var task in side.Tasks)
                    {
                        if (!_permission.Any(p => p.ProjectId.Equals(project_id) && p.UserId.Equals(task.AssignedUserId)))
                        {
                            throw NotFound(task.AssignedUserId, "assigned user id");
                        }
                    }
                }

                foreach (var side in model.Sides)
                {
                    foreach (var task in side.Tasks)
                    {
                        _task.Add(new Data.Models.Task
                        {
                            Detail   = task.Detail,
                            IsDelete = false,
                            Name     = task.Name,
                            SprintId = sprint_id,
                            Status   = "Incomplete",
                            UserId   = task.AssignedUserId,
                            Side     = side.Side
                        });
                    }
                }
                SaveChanges();

                return(GetAll(sprint_id));
            }
            catch (Exception e)
            {
                throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred while add tasks!",
                                                                         e, DateTime.Now, "Server", "Service_Task_AddMany");
            }
        }
        protected override IEnumerator ExecuteState(IContext context)
        {
            var gameField = context.Get <ConquerGameField>();

            var gameModel = new ConquerGameData(_fieldInfo);

            gameField.Initialize(gameModel.FieldModel);

            var playerModel      = new ConquerPlayerModel();
            var fieldCellFactory = new GameFieldCellFactory(_fieldInfo.CellsMap);

            var turn = playerModel.TurnModel.Value;

            turn.SelectedCell.Value = gameField.GetCell(0, 0);

            context.Add <IGameFieldCellFactory>(fieldCellFactory);
            context.Add(_fieldInfo);
            context.Add(playerModel);
            context.Add(gameModel);

            OutputContext.Add(context);

            yield break;
        }
Esempio n. 25
0
 public object Add(string third_party_account_id, string email, string name, string avatar_url, string access_token, Guid tool_id, Guid user_id)
 {
     try
     {
         Account account = _account.GetOne(a => a.ThirdPartyAccountId.Equals(third_party_account_id) && a.ToolId.Equals(tool_id));
         if (account == null)
         {
             account = _account.Add(new Account
             {
                 ToolId              = tool_id,
                 AccessToken         = access_token,
                 AvatarUrl           = avatar_url,
                 Email               = email,
                 IsMain              = false,
                 Name                = name,
                 ThirdPartyAccountId = third_party_account_id,
                 UserId              = user_id
             });
         }
         else
         {
             if (account.UserId != null)
             {
                 if (!account.UserId.Value.Equals(user_id))
                 {
                     throw BadRequest("This third party account has been connect to a Nococid account!\nKindly cancel the connection first!");
                 }
             }
             account.AccessToken = access_token;
             account.AvatarUrl   = avatar_url;
             account.Email       = email;
             account.Name        = name;
             account.UserId      = user_id;
         }
         SaveChanges();
         return(new
         {
             account.Email,
             account.Name,
             account.AvatarUrl
         });
     }
     catch (Exception e)
     {
         throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred while add token for a tool!",
                                                                  e, DateTime.Now, "Server", "Service_Token_Add");
     }
 }
Esempio n. 26
0
        public UserAuthorizationM Register(UserCreateM model, Guid?admin_user_id)
        {
            try
            {
                if (string.IsNullOrEmpty(model.Username) | string.IsNullOrEmpty(model.Password))
                {
                    throw BadRequest("The username or password not must emplty!");
                }
                if (_user.Any(u => u.Username.Equals(model.Username)))
                {
                    throw BadRequest("The username has been used!");
                }

                User user = _user.Add(new User
                {
                    Username    = model.Username,
                    Password    = NococidAuthentication.GetHashedPassword(model.Username, model.Password),
                    AdminUserId = admin_user_id
                });
                SaveChanges();
                UserAuthorizationM result = new UserAuthorizationM
                {
                    HasVscAccount = false,
                    User          = new UserM
                    {
                        Id       = user.Id,
                        Username = user.Username
                    }
                };
                if (admin_user_id != null)
                {
                    result.AdminUser = _user.Where(u => u.Id.Equals(admin_user_id))
                                       .Select(u => new UserM
                    {
                        Id       = u.Id,
                        Username = u.Username
                    }).FirstOrDefault();
                }

                return(result);
            }
            catch (Exception e)
            {
                throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred while register!",
                                                                         e, DateTime.Now, "Server", "Service_User_Register");
            }
        }
Esempio n. 27
0
        public void Add(GHWebhookPayload model)
        {
            try
            {
                string branch_name         = model.Ref.Substring(model.Ref.LastIndexOf("/") + 1);
                var    split               = model.Head_commit.Message.Split("\n\n");
                string commit_message      = split[0];
                string commit_message_body = split.Length == 2 ? split[1] : "";

                Guid?account_id = _account.Where(a => a.Name.Equals(model.Head_commit.Author.Username)).Select(a => a.Id).FirstOrDefault();
                if (account_id == null)
                {
                    throw NotFound(model.Head_commit.Author.Username, "github username");
                }
                Guid?branch_id = _branch.Where(b => b.Name.Equals(branch_name) && b.Repository.ThirdPartyRepositoryId.Equals(model.Repository.Id.ToString())).Select(b => b.Id).FirstOrDefault();
                if (branch_id == null)
                {
                    throw NotFound(branch_name, "branch name");
                }

                DateTime.TryParse(model.Head_commit.Timestamp, out DateTime commit_time);
                Guid commit_id = _commit.Add(new Commit
                {
                    Message          = commit_message,
                    MessageBody      = commit_message_body,
                    AccountId        = account_id,
                    PreviousCommitId = model.Before,
                    CurrentCommitId  = model.After,
                    BranchId         = branch_id,
                    IsSubmit         = false,
                    CommitTime       = commit_time
                }).Id;

                _submission.Add(new Submission
                {
                    Id = commit_id
                });
                SaveChanges();
            }
            catch (Exception e)
            {
                throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred while add commit!",
                                                                         e, DateTime.Now, "Server", "Service_Commit_Add");
            }
        }
Esempio n. 28
0
 public Guid Add(Guid pipeline_id, Guid submission_id, string test_type)
 {
     try
     {
         Test test = _test.Add(new Test
         {
             Id   = pipeline_id,
             Type = test_type
         });
         SaveChanges();
         return(test.Id);
     }
     catch (Exception e)
     {
         throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred while add a test!",
                                                                  e, DateTime.Now, "Server", "Service_Test_Add");
     }
 }
        public async Task <ActionResult <UserView> > Register([FromBody] AuthCredentials creds)
        {
            if (await db.Users.AnyAsync(u => u.LoginName == creds.LoginName))
            {
                return(BadRequest("login name already exists"));
            }

            var user = new User()
            {
                LoginName    = creds.LoginName,
                PasswordHash = hasher.HashFromPassword(creds.Password),
            };

            db.Add(user);
            await db.SaveChangesAsync();

            return(Created($"/api/users/{user.Id}", new UserView(user)));
        }
Esempio n. 30
0
 public Return.Return Add(IEntity value)
 {
     try
     {
         _context.Add(value);
         return(new Return.Return
         {
             ReturnType = ReturnType.Success
         });
     }
     catch (Exception e)
     {
         return(new Return.Return
         {
             Message = e.Message,
             ReturnType = ReturnType.Error
         });
     }
 }
Esempio n. 31
0
 public void AddCollab(Guid account_id, Guid repository_id)
 {
     try
     {
         Guid owner_id = _collaborator.Where(c => c.RepositoryId.Equals(repository_id) && c.AccountId.Equals(c.OwnerId))
                         .Select(c => c.OwnerId.Value).FirstOrDefault();
         _collaborator.Add(new Collaborator
         {
             AccountId    = account_id,
             RepositoryId = repository_id,
             OwnerId      = owner_id
         });
     }
     catch (Exception e)
     {
         throw e is RequestException ? e : _errorHandler.WriteLog("An error occurred while invite a member!",
                                                                  e, DateTime.Now, "Server", "Service_Collaborator_Add");
     }
 }
        /// <summary>
        /// Obtains and processes the chain of controllers servicing this request. If a transfer is requested
        /// during the processing of a controller, the computed chain of controllers finishes, and then a
        /// recursive call is made to process the new contrller.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="requestPoint">The request point.</param>
        /// <param name="requestContext">The request context.</param>
        public virtual void InvokeMethod(HttpContextBase context, string requestPoint, IContext requestContext)
        {
            logger.Report(Messages.ProcessingRequest, requestPoint);

            try
            {
                InvokeMethodDirect(context, requestPoint, requestContext);
            }
            catch (Exception ex)
            {
                if (!IsMethodDefinedExplicitly(Application.UnhandledException))
                    throw;

                requestContext.Clear();
                requestContext.Add("unhandledException", ex);

                InvokeMethodDirect(context, Application.UnhandledException, requestContext);
            }
        }
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        /// <summary>
        /// Obtains and processes the chain of controllers servicing this request. If a transfer is requested
        /// during the processing of a controller, the computed chain of controllers finishes, and then a
        /// recursive call is made to process the new contrller.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="requestPoint">The request point.</param>
        /// <param name="requestContext">The request context.</param>
        public virtual void InvokeMethod(HttpContextBase context, string requestPoint, IContext requestContext, bool handleException)
        {
            logger.Report(Messages.ProcessingRequest, requestPoint);

            try
            {
				List<ControllerInvocationInfo> invocationInfos = dispatcher.GetControllers(requestPoint);

				// TODO: this code should be replaced with call to the check method 
				// when it will be implemented on the dispatcher correctly
                if (invocationInfos.Count() == 0)
                {
                    logger.Report(Messages.ControllerNotFound, requestPoint);
                    throw new WebException(StatusCode.NotFound, String.Format("'{0} could not be found", requestPoint));
                }

				StringBuilder path = new StringBuilder();
				foreach (ControllerInvocationInfo info in invocationInfos)
					path.Append(info.BindPoint.Controller.ControllerTypeName).Append(" based on ").Append(info.BindPoint.Target).Append("\r\n");

				logger.Report(Messages.ExecutionPath, requestPoint, path.ToString());


				bool securityCheckComplete = false;
				bool securityCheckFailed = false;
				var failedPermissions = new Dictionary<string, KeyValuePair<FailAction, string>>();

				Stopwatch sw = new Stopwatch();
				Stopwatch sw1 = new Stopwatch();

				foreach (ControllerInvocationInfo invocationInfo in invocationInfos)
                {
					sw.Reset();
					sw.Start(); 
					
					
					IController controller = manager.GetController(invocationInfo, context, requestContext);

					try
					{
						// all security controllers are guaranteed to be at the top of the list, in proper order.
						// we need to run through all of them, because an inner controller may override the decision 
						// of an outer controller. therefore, the final decision is deferred until all security checks
						// have passed
						if (!securityCheckComplete)
						{
							ISecurityController securityController = controller as ISecurityController;
							if (securityController == null)
								securityCheckComplete = true;
							else
							{
								// this needs to run prior to the check
								controller.ProcessRequest(context, requestContext);

								// we only care about the actual return value of the last controller, as intermediate
								// results can be overriden by subsequent controllers. discard intermediate return values.
								securityCheckFailed = !securityController.HasAccess(requestContext, failedPermissions);
							}
						}

						// we have to do the check a second time, because the securityCheckComplete flag
						// gets set inside the top if. doing this in an else up top would skip the first
						// non-security controller
						if (securityCheckComplete)
						{
							if (securityCheckFailed || failedPermissions.Count != 0)
							{
								StringBuilder builder = new StringBuilder();
								foreach (string perm in failedPermissions.Keys)
									builder.AppendLine(perm);

								foreach (KeyValuePair<FailAction, string> kvp in failedPermissions.Values)
									if (kvp.Key == FailAction.Redirect)
									{
										// currently you can only house one transfer request per context, 
										// however, that may change in the future.
										requestContext.ClearTransferRequest();

										// give the fail action target a chance to redirect after re-validating
										requestContext.Transfer(
											kvp.Value +
											(kvp.Value.Contains("?") ? "&" : "?") +
											"originalRequest=" +
											HttpUtility.UrlEncode(requestPoint));

										logger.Report(Messages.SecurityRedirect, kvp.Value, builder.ToString());
										break;
									}

                                if (!requestContext.TransferRequested)
                                    throw new WebException(StatusCode.Unauthorized, "Access denied");
                                else
                                    // break out of the controller loop. we shouldn't be processing any more
                                    // controllers for this request, and need to get into whatever the security
                                    // guys requested
                                    break;
                            }
                            else
                            {
								if (invocationInfo.BindPoint.Controller.DefaultTemplates.Count > 0)
									requestContext.Response.RenderWith(invocationInfo.BindPoint.Controller.DefaultTemplates);

								sw1.Reset();
								sw1.Start();
								controller.ProcessRequest(context, requestContext);
								sw1.Stop();

							}
						}
					}
					finally
					{
						manager.ReturnController(controller, context, requestContext);
						sw.Stop();
						logger.Report(Messages.ControllerInvoked, sw.ElapsedMilliseconds.ToString(),sw1.ElapsedMilliseconds.ToString(), invocationInfo.BindPoint.Controller.ControllerTypeName);

					}
				}

				if (requestContext.TransferRequested)
				{
					string transferRequestPoint = BindPointUtilities.VerbQualify(requestContext.TransferTarget, "get");
					requestContext.ClearTransferRequest();

                    InvokeMethod(context, transferRequestPoint, requestContext);
                }
            }
            catch (Exception ex)
            {
				try
				{
					logger.Report(Messages.UnhandledException,ex.Message,ex.StackTrace);
				}
				catch
				{}

                //Assume that there are some other ctrls which match UnhandledException url and cause an exception.
                //In this case, removing this check may cause an infinite recursion of InvokeMethod and StackOverflow at the end.
                if (handleException)
                    throw new ApplicationException("Cannot process UnhandledException url, maybe some other controllers also match this url and cause an exception", ex);

				if (!IsMethodDefinedExplicitly(Application.UnhandledException))
				{
					throw new ApplicationException("Unhandled exception, and no binding to " + Application.UnhandledException + " found.", ex);
				}

                requestContext.Clear();
                requestContext.Add("unhandledException", ex);

				InvokeMethod(context, Application.UnhandledException, requestContext, true);
                
			}
        }
 public bool Execute(IContext context)
 {
     context.Add(FILTER_KEY, this);
     return false;
 }