public async Task <ActionResult> Delete(string id)
        {
            if (id != null)
            {
                _Connection.DatabaseConnection();
                _Metadata.SetDatabase(_Connection.GetDatabase()); //Estabeleçe a conexão;
                _GetBranchById.SetDatabase(_Connection.GetDatabase());
                _GetStateById.SetDatabase(_Connection.GetDatabase());
                //_Metadata.ReadFromDatabase();
                MetadataModel model = _Metadata.GetMetadata(id);

                _GetBranchById.ReadFromDatabase(model.Branch);
                _GetStateById.ReadFromDatabase(model.State);

                ViewMetadataModel ModelToDelete = new ViewMetadataModel()
                {
                    Id      = model.Id,
                    Name    = model.Name,
                    Version = model.Version.ToString(),
                    Date    = model.Date.ToString(),
                    Branch  = _GetBranchById.GetBranches(),
                    State   = _GetStateById.GetStateDescription()
                };
                return(await Task.Run(() => View("Delete", ModelToDelete)));
            }
            return(await Task.Run(() => View("Delete")));
        }
        public async Task <ActionResult> GetDetailsByName(string name)
        {
            if (name == null)
            {
                return(BadRequest());
            }

            //------------------------------------------
            //Add - Pagination to Page (Phase 1)
            //------------------------------------------
            string pageNumber = Request.Query["Page"];

            if (string.IsNullOrEmpty(pageNumber))
            {
                pageNumber = 1.ToString();
            }
            int pageIndex = Convert.ToInt32(pageNumber);

            ViewBag.PageNumber = pageNumber;
            //------------------------------------------

            _Connection.DatabaseConnection();
            _Metadata.SetDatabase(_Connection.GetDatabase());
            _GetBranchById.SetDatabase(_Connection.GetDatabase());
            _GetStateById.SetDatabase(_Connection.GetDatabase());

            List <MetadataModel>     modelList      = _Metadata.GetProcessByName(name);
            List <ViewMetadataModel> _ViewModelList = new List <ViewMetadataModel>();

            ViewBag.Name = modelList[0].Name; //Stores the process name;

            foreach (var model in modelList)
            {
                _GetBranchById.ReadFromDatabase(model.Branch);
                _GetStateById.ReadFromDatabase(model.State);
                ViewMetadataModel _details = new ViewMetadataModel()
                {
                    Id      = model.Id,
                    Name    = model.Name,
                    Version = model.Version.ToString(),
                    Date    = model.Date.ToString(),
                    Branch  = _GetBranchById.GetBranches(),
                    State   = _GetStateById.GetStateDescription(),
                };
                _ViewModelList.Add(_details);
            }

            //------------------------------------------
            //Add - Pagination to Page (Phase 2)
            //------------------------------------------
            _SetPagination.SetNumberOfModelsByPage(2);
            Dictionary <int, List <ViewMetadataModel> > modelsToDisplay = _SetPagination.SetModelsByPage(_ViewModelList);
            int NumberOfPages = modelsToDisplay.Count();

            ViewBag.NumberOfPages = NumberOfPages;
            //------------------------------------------
            return(await Task.Run(() => View("GetDetailsByName", modelsToDisplay[pageIndex])));
        }
        public async Task <ActionResult> Update()
        {
            string processName = Request.Query["ProcessName"];

            if (string.IsNullOrEmpty(processName))
            {
                return(BadRequest());
            }

            _Connection.DatabaseConnection();                   //Estabeleçe a ligação / conexão com a base de dados;
            _KeyID.SetKey();                                    //Cria um novo objectId para identificar univocamente o processo na base de dados;
            _Metadata.SetDatabase(_Connection.GetDatabase());   //Cria uma instância da base de dados no serviço de Metadados;
            _Validation.SetDatabase(_Connection.GetDatabase()); //Cria uma instância da base de dados no serviço de validação;
            _GetStateById.SetDatabase(_Connection.GetDatabase());
            _GetBranchById.SetDatabase(_Connection.GetDatabase());


            //1º Passo - Obter a última versão deste processo
            int lastVersion = _Validation.GetProcessLastVersion(processName);

            //2º Passo - Obter o processo anterior ao momento em que sofre uma atualização
            MetadataModel model = _Metadata.GetProcessByVersion(processName, lastVersion);

            _GetBranchById.ReadFromDatabase(model.Branch);

            //3º Passo - Construir o modelo de dados View Metadata Model
            ViewMetadataModel modelToDisplay = new ViewMetadataModel()
            {
                Id      = _KeyID.GetKey(),                 //4º Passo - Atualizar o ID do processo, pois trata-se de um processo independente;
                Name    = model.Name,
                Version = (model.Version += 1).ToString(), //5º Passo - Atualizar a versão do processo, para uma versão superior incrementando o número da mesma;
                Date    = DateTime.Now.ToString().Substring(0, 10),
                State   = _GetStateById.GetStateDescription(),
                Branch  = _GetBranchById.GetBranches(),
            };

            string fields = string.Empty;

            //6º Passo - Obter os ids dos fields agregados ao processo
            for (int j = 0; j < model.Field.Count(); j++)
            {
                if (j == model.Field.Count() - 1)
                {
                    fields += model.Field.ElementAt(j);
                }
                else
                {
                    fields += (model.Field.ElementAt(j) + ";");
                }
            }

            ViewBag.Fields = fields;

            return(await Task.Run(() => View("Update", modelToDisplay)));
        }
        public async Task <ActionResult> SelectBranch(string processId, string processName, string processVersion, string processDate, string processBranches, string processState, string isReadonly)
        {
            ViewMetadataModel viewModel = new ViewMetadataModel()
            {
                Id      = processId,
                Name    = processName,
                Version = processVersion,
                Date    = processDate,
                Branch  = processBranches,
                State   = processState
            };

            ViewBag.IsReadonly = isReadonly;

            return(await Task.Run(() => View("SelectBranch", viewModel)));
        }
        public async Task <ActionResult> Read()
        {
            //Stores data in cache;
            TempData["Name"] = Request.Query["Name"];
            string searchName = TempData["Name"].ToString();

            ViewBag.Name = searchName;

            TempData["Version"] = Request.Query["Version"];
            string searchVersion = TempData["Version"].ToString();

            ViewBag.Version = searchVersion;

            string pageNumber = Request.Query["Page"];

            if (string.IsNullOrEmpty(pageNumber))
            {
                pageNumber = 1.ToString();
            }

            int pageIndex = Convert.ToInt32(pageNumber);

            if (string.IsNullOrEmpty(searchName))
            {
                searchName = null;
            }
            //No caso de a string que representa a informação do filtro de pesquisa por versão, ser nula ou vazia,
            //define-se como valor default a versão 1;
            if (string.IsNullOrEmpty(searchVersion))
            {
                searchVersion = null;
            }

            ViewBag.PageNumber = pageNumber;

            _Connection.DatabaseConnection();
            _Metadata.SetDatabase(_Connection.GetDatabase()); //Estabeleçe a conexão;
            _GetBranchById.SetDatabase(_Connection.GetDatabase());
            _GetStateById.SetDatabase(_Connection.GetDatabase());

            _Metadata.SetFilterParameters(searchName, searchVersion);
            _Metadata.ReadFromDatabase();

            List <MetadataModel>     metadataList = _Metadata.GetProcessesMetadataList();
            List <ViewMetadataModel> viewModels   = new List <ViewMetadataModel>();

            if (metadataList != null)
            {
                foreach (var metadata in metadataList)
                {
                    _GetBranchById.ReadFromDatabase(metadata.Branch);
                    _GetStateById.ReadFromDatabase(metadata.State);

                    ViewMetadataModel viewModel = new ViewMetadataModel()
                    {
                        Id      = metadata.Id,
                        Name    = metadata.Name,
                        Version = metadata.Version.ToString(),
                        Date    = metadata.Date.ToString(),
                        Branch  = _GetBranchById.GetBranches(),
                        State   = _GetStateById.GetStateDescription()
                    };

                    viewModels.Add(viewModel);
                }
            }
            _SetPagination.SetNumberOfModelsByPage(4);
            Dictionary <int, List <ViewMetadataModel> > modelsToDisplay = _SetPagination.SetModelsByPage(viewModels);

            int NumberOfPages = modelsToDisplay.Count();

            ViewBag.NumberOfPages = NumberOfPages;


            //Se a base de dados não tiver processos armazenados para mostrar na listagem de processos;
            if (modelsToDisplay.Count() == 0)
            {
                List <ViewMetadataModel> models = new List <ViewMetadataModel>();
                ViewMetadataModel        model  = new ViewMetadataModel()
                {
                    Id      = string.Empty,
                    Name    = string.Empty,
                    Version = string.Empty,
                    Date    = string.Empty,
                    Branch  = string.Empty,
                    State   = string.Empty
                };
                models.Add(model);
                return(await Task.Run(() => View("Read", models)));
            }

            return(await Task.Run(() => View("Read", modelsToDisplay[pageIndex])));
        }
        public async Task <ActionResult> WebFormGenerator(ViewMetadataModel model)
        {
            List <WebFormModel> webFormElements = new List <WebFormModel>();

            //Se o modelo de dados for nulo, logo estamos perante um caso de pedido inválido (Bad Request)
            if (model == null)
            {
                return(BadRequest());
            }

            if (model.Branch == null)
            {
                return(await Task.Run(() => Redirect("/Metadata/SelectBranch?processId=" + model.Id + "&processName=" + model.Name + "&processVersion=" + model.Version + "&processDate=" + model.Date + "&processBranches=" + model.Branch + "&processState=" + model.State + "&isReadonly='true'")));
            }

            //Valores para preenchimento de campos hidden no formulário gerado automaticamente;
            ViewBag.ObjectId       = null;
            ViewBag.ProcessId      = model.Id;
            ViewBag.ProcessVersion = model.Version;
            ViewBag.ProcessBranch  = model.Branch;

            string ProcessFields = string.Empty;

            _Connection.DatabaseConnection();

            //Chamadas aos serviços - Ligação à base de dados
            _Metadata.SetDatabase(_Connection.GetDatabase());
            _Field.SetDatabase(_Connection.GetDatabase());
            _Properties.SetDatabase(_Connection.GetDatabase());
            _Data.SetDatabase(_Connection.GetDatabase());

            List <string> fields = _Metadata.GetProcessFieldsID(model.Id); //Obter os campos existentes no processo seleccionado;

            for (int j = 0; j < fields.Count; j++)
            {
                FieldModel fieldModel = _Field.GetField(fields.ElementAt(j));

                if (j == fields.Count - 1)
                {
                    ProcessFields += fieldModel.Type;
                }
                else
                {
                    ProcessFields += fieldModel.Type + " ";
                }

                PropertiesModel propertiesModel = _Properties.GetProperties(fieldModel.Properties);

                WebFormModel webFormElement = new WebFormModel()
                {
                    Type      = fieldModel.Type,
                    Name      = fieldModel.Name,
                    Size      = propertiesModel.Size.ToString(),
                    Value     = string.Empty,
                    Maxlength = propertiesModel.Maxlength.ToString(),
                    Required  = propertiesModel.Required.ToString(),
                    Readonly  = model.State.Equals("true") ? true : false
                };

                webFormElements.Add(webFormElement);
            }

            ViewBag.Readonly = model.State.Equals("true") ? "true" : "false";

            //Passar a lista de webform elements a uma classe que vai criar uma array com as linhas a serem renderizadas;
            WebFormTemplate webFormTemplate = new WebFormTemplate(webFormElements);
            List <string>   fragments       = webFormTemplate.Template();

            string template = string.Empty;

            for (int j = 0; j < fragments.Count; j++)
            {
                if (j == fragments.Count - 1)
                {
                    template += fragments[j];
                }
                else
                {
                    template += (fragments[j] + "|");
                }
            }

            ViewBag.Template = template;

            return(await Task.Run(() => View("WebFormGenerator")));
        }