Exemplo n.º 1
0
        public void HorarioBrasilia_RetornaHorarioCorreto()
        {
            // Arrange // Act
            var data = HelpersMethods.HorarioBrasilia();

            // Assert
            Assert.IsTrue(DateTime.Now.Subtract(data) < TimeSpan.FromSeconds(1));
        }
Exemplo n.º 2
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var user = BLUser <ETUserPublic> .GetLogged();

            if (user != null)
            {
                filterContext.Result = new RedirectResult(HelpersMethods.GetLastUrl());
            }
        }
Exemplo n.º 3
0
        } // Add

        // Add Tail mode.  This closes the current OPC Interval
        // and start a new one.
        public int AddTail(OPCBindingModel opc)
        {
            SqlConnection conn = new SqlConnection(_InCConnString);
            SqlCommand    cmd  = new SqlCommand();

            int    errcode  = 1;
            string errmsg   = "INSERT_Tail ERROR";
            int    newOPCID = 0;

            using (conn)
            {
                conn.Open();

                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "API_OPC_INSERT_proc_Tail";
                cmd.Connection  = conn;

                HelpersMethods.AddParamToSQLCmd(cmd, "@opcid", SqlDbType.Int, 8, ParameterDirection.Input, opc.OPCID);
                HelpersMethods.AddParamToSQLCmd(cmd, "@cc", SqlDbType.Int, 8, ParameterDirection.Input, opc.CC);
                HelpersMethods.AddParamToSQLCmd(cmd, "@cat", SqlDbType.NVarChar, 15, ParameterDirection.Input, opc.Cat);
                HelpersMethods.AddParamToSQLCmd(cmd, "@secs", SqlDbType.Int, 8, ParameterDirection.Input, opc.Secs);

                HelpersMethods.AddParamToSQLCmd(cmd, "@errcode", SqlDbType.Int, 8, ParameterDirection.Output);
                HelpersMethods.AddParamToSQLCmd(cmd, "@errmsg", SqlDbType.NVarChar, 50, ParameterDirection.Output);

                HelpersMethods.AddParamToSQLCmd(cmd, "@newid", SqlDbType.Int, 8, ParameterDirection.Output);

                cmd.ExecuteNonQuery();

                // Assign output parameters to variables
                errcode  = Convert.ToInt32(cmd.Parameters["@errcode"].Value);
                errmsg   = Convert.ToString(cmd.Parameters["@errmsg"].Value);
                newOPCID = Convert.ToInt32(cmd.Parameters["@newid"].Value);

                conn.Close();
            }

            // ---------------------------------------------
            // Throw expection if errcode <> 0 OR OPCID = 0
            // ---------------------------------------------
            if (errcode != 0)
            {
                throw new Exception(errmsg);
            }
            else if (newOPCID == 0)
            {
                throw new Exception(errmsg);
            }
            else
            {
                return(newOPCID);
            }
        } // AddTail
        internal static void Response(Section section, string name)
        {
            try
            {
                //Create list of skills
                List <string> skillsList = new List <string>();
                List <string> expList    = new List <string>();
                //Get text from tables
                skillsList = HelpersMethods.GetTextFromTable(section.Tables[0]); //table with skills
                expList    = HelpersMethods.GetTextFromTable(section.Tables[1]); // table with exp
#if OLD_PARSE_DEBUG_SKILL
                foreach (string s in skillsList)
                {
                    Console.WriteLine(s);
                }
#endif
#if OLD_PARSE_DEBUG_EXP
                foreach (string s in expList)
                {
                    Console.WriteLine(s);
                }
#endif
                Console.WriteLine("Parse complete " + name);
                //Split and save exp
                var expModelList = Helpers.ProcessExps.ProccExp(expList);
                expModelList.AddRange(ProcessSkills.ProccSkills(skillsList));
                //Processing and save expearence
#if OLD_PARSE_DEBUG_SKILLS_AND_EXP
                foreach (ModelSkill s in skillsModelList)
                {
                    Console.WriteLine(s.name + " " + s.level + " " + s.type + " " + s.allNames.Count.ToString());
                }
#endif


                //HelpersMethods.DeleteSimilarSkills(ref expModelList);
                //HelpersMethods.CheckLeadSkill(ref expModelList);
                string         connectionString = "mongodb://*****:*****@ds046667.mlab.com:46667/workers_db";
                MongoClient    client           = new MongoClient(connectionString);
                IMongoDatabase database         = client.GetDatabase("workers_db");
                database.CreateCollection(name);
                var colSkills = database.GetCollection <ModelSkill>(name);
                var colLevels = database.GetCollection <SkillLevel>(name + "Lvl");
                var data      = HelpersMethods.ToModelSkills(expModelList);
                colSkills.InsertMany(data.Item1.ToArray());
                colLevels.InsertMany(data.Item2.ToArray());
            }
            catch (Exception ex)
            {
                Console.WriteLine("EXCEPTION HERE " + name + "\n" + ex.Message);
            }
        }
Exemplo n.º 5
0
 public virtual void NewAccount(VM2 model)
 {
     if (ModelState.IsValid)
     {
         if (BLUser <ET> .Create(HelpersMethods.CopyValues <VM2, ET>(model)))
         {
             this.AddToastMessage("Sucesso", "Conta criada com sucesso", ToastrType.Success);
         }
         else
         {
             this.AddToastMessage("Erro", "Erro ao registrar, favor tentar novamente", ToastrType.Error);
         }
     }
 }
Exemplo n.º 6
0
        public virtual ActionResult Item(VM model)
        {
            if (ModelState.IsValid)
            {
                if (BLAdminBase <ET> .Save(HelpersMethods.CopyValues <VM, ET>(model)))
                {
                    this.AddToastMessage("Sucesso", "Salvo com sucesso.", ToastrType.Success);
                }
                else
                {
                    this.AddToastMessage("Erro", "Erro ao salvar.", ToastrType.Error);
                }
            }

            return(RedirectToAction("Index"));
        }
Exemplo n.º 7
0
        public VotoBranco RegistrarVotoBranco(VotoBranco voto)
        {
            EleicoesService eleicoesService = new EleicoesService();

            voto.IP          = HttpContext.Current.Request.UserHostAddress;
            voto.DataHorario = HelpersMethods.HorarioBrasilia();

            if (!eleicoesService.FuncionarioExiste(voto.CodigoEleicao, voto.FuncionarioIdEleitor))
            {
                throw new FuncionarioNaoEncontradoException(voto.FuncionarioIdEleitor);
            }

            db.VotosBrancos.Add(voto);
            db.SaveChanges();

            return(voto);
        }
Exemplo n.º 8
0
        public Airline(int number, string departedDaT, string arrivedDaT, string departedCity, string arrivedCity,
                       int terminalNumber, int gateNumber, PlaneEnum planeType)
        {
            var helper = new HelpersMethods();

            Number         = number;
            DepartedCity   = departedCity;
            ArrivedCity    = arrivedCity;
            TerminalNumber = terminalNumber;
            Planes         = new Plane.PlaneController()[planeType];
            helper.StringToDateTime(departedDaT, out DepartedDateTime);
            helper.StringToDateTime(arrivedDaT, out ArrivedDateTime);
            GateNumber = gateNumber;
            Status     = SetAirlineStatus();
            FreeBSeats = Planes.BSeats;
            FreeESeats = Planes.ESeats;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Add a new Node to the list.
        /// </summary>
        public void Add(NPOI_Node content)
        {
            size++;
            Node tempCurrent = current;

            var rowTypeString = HelpersMethods.StringArrayToString(content.Cells.Select(x => x.CellType.ToString()).ToArray());

            var rowValueString = HelpersMethods.StringArrayToString(content.Cells.Select(x => HelpersMethods.GetICellStringValue(x)).ToArray());

            var typeHash   = HelpersMethods.GetMD5(Encoding.ASCII.GetBytes(rowTypeString));
            var valuesHash = HelpersMethods.GetMD5(Encoding.ASCII.GetBytes(rowValueString));

            // This is a more verbose implementation to avoid adding nodes to the head of the list
            var node = new Node()
            {
                NodeContent = content,
                TypesHash   = typeHash,
                ValuesHash  = valuesHash
            };

            if (head == null)
            {
                // This is the first node. Make it the head
                head = node;
            }
            else
            {
                // This is not the head. Make it current's next node.
                current.Next  = node;
                node.Previous = tempCurrent;
            }

            // Makes newly added node the current node
            current = node;


            // This implementation is simpler but adds nodes in reverse order. It adds nodes to the head of the list

            //head = new Node()
            //{
            //    Next = head,
            //    NodeContent = content
            //};
        }
Exemplo n.º 10
0
        private void _buildHeadersCombinationFromAttributes()
        {
            PropertyInfo[] props = _model.GetProperties();

            // convert to dictionary
            var headders = props
                           .Where(x => x.GetCustomAttribute <TableHeader>() != null)
                           .Select
                           (
                x => new KeyValuePair <int, KeyValuePair <string, string[]> >
                (
                    x.GetCustomAttribute <TableHeader>().Index,
                    new KeyValuePair <string, string[]>(x.Name, x.GetCustomAttribute <TableHeader>().Headers)
                )
                           )
                           .OrderBy(x => x.Key)
                           .ToList();

            // possible combination count & check

            //var combinationPerProperty = headders
            //    .Select(x => x.Value.Value.Length)
            //    .ToArray<int>();

            //int combinationCount = combinationPerProperty.Aggregate(1, (a, b) => a * b);

            List <string[]> combinations = _getCombinations(headders);

            _headersCombinationsHash = _getCombinations(headders).Select(x =>
            {
                byte[] headder = Encoding.ASCII.GetBytes(HelpersMethods.StringArrayToString(x.ToArray()));
                return(HelpersMethods.GetMD5(headder));
            }).ToArray <string>();


            _headderMap = _getCombinations(headders).ToDictionary(k =>
            {
                return(HelpersMethods.GetMD5(Encoding.ASCII.GetBytes(HelpersMethods.StringArrayToString(k.ToArray()))));
            }
                                                                  , v => v.ToArray());
        }
Exemplo n.º 11
0
        private void LoadAll()
        {
            HelpersMethods.TryFunc(context.Areas.Load);
            HelpersMethods.TryFunc(context.Planes.Load);
            HelpersMethods.TryFunc(context.Rockets.Load);
            HelpersMethods.TryFunc(context.Products.Load);
            HelpersMethods.TryFunc(context.Brigades.Load);
            HelpersMethods.TryFunc(context.Cehs.Load);
            HelpersMethods.TryFunc(context.EngTehProfs.Load);
            HelpersMethods.TryFunc(context.EngTehWorkers.Load);
            HelpersMethods.TryFunc(context.EngTehWorkerProfs.Load);
            HelpersMethods.TryFunc(context.Profs.Load);
            HelpersMethods.TryFunc(context.TestEquipments.Load);
            HelpersMethods.TryFunc(context.Testers.Load);
            HelpersMethods.TryFunc(context.TestLabs.Load);
            HelpersMethods.TryFunc(context.Works.Load);
            HelpersMethods.TryFunc(context.Workers.Load);
            HelpersMethods.TryFunc(context.WorkerProfs.Load);

            areaViewSource.Source             = context.Areas.Local;
            planesViewSource.Source           = context.Planes.Local;
            rocketViewSource.Source           = context.Rockets.Local;
            productViewSource.Source          = context.Products.Local;
            brigadeViewSource.Source          = context.Brigades.Local;
            cehViewSource.Source              = context.Cehs.Local;
            engTehProfViewSource.Source       = context.EngTehProfs.Local;
            engTehWorkerViewSource.Source     = context.EngTehWorkers.Local;
            engTehWorkerProfViewSource.Source = context.EngTehWorkerProfs.Local;
            profViewSource.Source             = context.Profs.Local;
            testEquipmentViewSource.Source    = context.TestEquipments.Local;
            testerViewSource.Source           = context.Testers.Local;
            testLabViewSource.Source          = context.TestLabs.Local;
            workViewSource.Source             = context.Works.Local;
            workerViewSource.Source           = context.Workers.Local;
            workerProfViewSource.Source       = context.WorkerProfs.Local;
        }
Exemplo n.º 12
0
 public static int MinEven(List <int> numbers)
 {
     return(HelpersMethods.FindMinEvenNumber(numbers));
 }
Exemplo n.º 13
0
        //private IEnumerable<T> _parseFile<T>(Metadata<T> metadata, byte[] rawData)
        //{
        //    var parsedData = new List<T>();

        //    //create parser
        //    try
        //    {
        //        using (var stream = new MemoryStream(rawData))
        //        {
        //            XSSFWorkbook hssfwb = new XSSFWorkbook(stream);

        //            for (int i = 0; i < hssfwb.NumberOfSheets; i++)
        //            {
        //                XSSFSheet sheet = (XSSFSheet)hssfwb.GetSheetAt(i);

        //                System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
        //                rows.MoveNext();
        //                XSSFRow row = (XSSFRow)rows.Current;

        //                _headerList = _getHeaderList(row);
        //                _headerLookup = LNGProvider_Parser_HeaderLookup.BuildHeaderLookup(_headerList, metadata);

        //                if (_headerList == null)
        //                    throw new Exception("Unable to find Header row");

        //                while (rows.MoveNext())
        //                {
        //                    row = (XSSFRow)rows.Current;

        //                    ParsedRowList.Add(LNGProvider_Parser_Mapper._buildLNGFileValueDailyTotal(row, _headerLookup, LNGProvider_Parser_Constants.Countries[i]));

        //                }

        //            }

        //        }
        //        parsedData.ParsedData = ParsedRowList.ToArray();
        //        parsedData.RawData = rawData;

        //        return parsedData;
        //    }
        //    catch (Exception ex)
        //    {
        //        parsedData.RawData = rawData;
        //        return parsedData;
        //    }

        //    throw new NotImplementedException();
        //}

        private void _scan()
        {
            try
            {
                using (var stream = new MemoryStream(File.ReadAllBytes("c:\\Users\\Peter Vargovcik\\Documents\\Visual Studio 2015\\Projects\\SmartParser\\SmartParser\\Files\\daily_totals_2012-2014.xlsx")))
                {
                    XSSFWorkbook hssfwb = new XSSFWorkbook(stream);

                    Dictionary <XSSFRow, IEnumerable <XSSFRow> > rowDictionary = new Dictionary <XSSFRow, IEnumerable <XSSFRow> >();
                    string previousHash = "";

                    for (int i = 0; i < hssfwb.NumberOfSheets; i++)
                    {
                        XSSFSheet sheet = (XSSFSheet)hssfwb.GetSheetAt(i);

                        IEnumerator rows = sheet.GetRowEnumerator();

                        int rowNumber = 0;

                        while (rows.MoveNext())
                        {
                            XSSFRow row = (XSSFRow)rows.Current;
                            _linkedList.Add(row);

                            Console.Write("Sheet : {0}, Line {1}, ", sheet.SheetName, rowNumber);

                            // hash of the row types
                            var rowTypeString = String.Join("-", row.Cells.Select(x => x.CellType.ToString()).ToArray());

                            var currentHashRow = HelpersMethods.GetMD5(Encoding.ASCII.GetBytes(rowTypeString));

                            if (_hashNotSame(previousHash, currentHashRow))
                            {
                                rowDictionary.Add(row, new List <XSSFRow>());
                            }
                            else
                            {
                                IEnumerable <XSSFRow> list = rowDictionary.Last().Value;
                                ((List <XSSFRow>)list).Add(row);
                            }


                            //for (int j = 0; j < row.Cells.Count; j++)
                            //{
                            //    Console.Write("[{0} : {1}], ", j, row.Cells[j].CellType.ToString());
                            //}

                            //Console.WriteLine();

                            //var firstCell = row.Cells[0].CellType;
                            //Console.WriteLine(firstCell.ToString());
                            rowNumber++;
                            previousHash = currentHashRow;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <HttpResponseMessage> AddOrUpdateCandidato()
        {
            try
            {
                FuncionariosService funcService = new FuncionariosService();

                // Verifica se request contém multipart/form-data.
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                //Diretório App_Data, para salvar o arquivo temporariamente
                string root     = HttpContext.Current.Server.MapPath("~/App_Data");
                var    provider = new MultipartFormDataStreamProvider(root);

                // Lê o arquivo da requisição assincronamente
                await Request.Content.ReadAsMultipartAsync(provider);

                //Deserializa os dados do Candidato
                JavaScriptSerializer json_serializer = new JavaScriptSerializer();
                var obj = json_serializer.DeserializeObject(provider.FormData.Get("candidato")) as Dictionary <string, object>;

                Image thumbnail = null;
                Image img       = null;
                try
                {
                    //Lê a foto do candidato

                    var httpPostedFile = HttpContext.Current.Request.Files["foto"];
                    if (httpPostedFile != null)
                    {
                        int length = httpPostedFile.ContentLength;
                        var bytes  = new byte[length]; //get imagedata
                        httpPostedFile.InputStream.Read(bytes, 0, length);
                        var stream = new MemoryStream(bytes);
                        img       = Image.FromStream(stream, false, false);
                        img       = ImageService.EnquadrarImagem((Bitmap)img);
                        thumbnail = ImageService.GetThumbnail(img, 75, 75);
                        stream.Dispose();
                        if (img.Height > 350)
                        {
                            img = ImageService.GetThumbnail(img, 350, 350);
                        }
                    }
                }
                catch
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, $"Erro ao processar imagem. Por favor, escolha outra! "));
                }

                int funcionarioId = int.Parse(obj["FuncionarioId"].ToString());
                //Cria uma instância de Funcionario
                Funcionario funcionario = null;
                try
                {
                    funcionario = funcService.GetFuncionario(funcionarioId);
                }
                catch (FuncionarioNaoEncontradoException)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Funcionário não encontrado!"));
                }

                funcionario.Login        = obj["LoginFuncionario"].ToString();
                funcionario.Nome         = obj["NomeFuncionario"].ToString();
                funcionario.Cargo        = obj["CargoFuncionario"].ToString();
                funcionario.Area         = obj["AreaFuncionario"].ToString();
                funcionario.Email        = obj["EmailFuncionario"].ToString();
                funcionario.Sobre        = (obj.ContainsKey("Sobre") && obj["Sobre"] != null) ? obj["Sobre"].ToString() : null;
                funcionario.DataAdmissao = DateTime.Parse(obj["DataAdmissaoFuncionario"].ToString());
                funcionario.Thumbnail    = ImageService.ConvertImageByte(thumbnail);

                funcService.AddOrUpdateFuncionario(funcionario);

                FuncionarioFoto funcFoto = new FuncionarioFoto
                {
                    FuncionarioId = funcionario.Id,
                    Foto          = ImageService.ConvertImageByte(img)
                };

                funcService.AddOrUpdateFuncionarioFoto(funcFoto);
                bool?validado = null;
                //if (User.IsInRole("Administrador")) validado = true;

                //Cria uma intância do candidato
                Candidato c = new Candidato
                {
                    FuncionarioId      = funcionarioId,
                    CodigoEleicao      = int.Parse(obj["CodigoEleicao"].ToString()),
                    HorarioCandidatura = HelpersMethods.HorarioBrasilia(),
                    Validado           = validado
                };

                //Tenta salvar as atualizações
                try
                {
                    c = candidatosService.AddOrUpdateCandidato(c);
                    candidatosService.ExcluirMotivoReprovacao(c);
                    //Excluir o arquivo
                    File.Delete(provider.FileData[0].LocalFileName);
                }
                catch (FuncionarioNaoCadastradoEleicaoException)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Você não está inscrito nessa eleição! Contate o administrador."));
                }
                catch (FuncionarioNaoElegivelException e)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message));
                }
                catch
                {
                    return(Request.CreateResponse(HttpStatusCode.InternalServerError, "Ocorreu um erro desconhecido. Por favor, entre em contato com o suporte."));
                }

                return(Request.CreateResponse(HttpStatusCode.OK, new CandidatoDTO(c)));
            }
            catch
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, "Ocorreu um erro desconhecido. Por favor, entre em contato com o suporte."));
            }
        }
Exemplo n.º 15
0
 public static double DivPI(List <int> numbers)
 {
     return(HelpersMethods.dividedWithP1(numbers));
 }
Exemplo n.º 16
0
        public virtual ActionResult Item(decimal?id)
        {
            var model = CRUD <ET> .Find(id.GetValueOrDefault(0));

            return(View(HelpersMethods.CopyValues <ET, VM>(model)));
        }
Exemplo n.º 17
0
 public static decimal Avg(List <int> numbers)
 {
     return(HelpersMethods.CalculateAverage(numbers));
 }
Exemplo n.º 18
0
 public static void ShowTextNum(List <int> numbers)
 {
     HelpersMethods.TextNum(numbers);
 }
Exemplo n.º 19
0
 public static List <int> Duplicate(List <int> numbers)
 {
     return(HelpersMethods.DuplicateListOfInt(numbers));
 }
Exemplo n.º 20
0
 public static bool EvenIs(int num)
 {
     return(HelpersMethods.ReturneIsEven(num));
 }
Exemplo n.º 21
0
 public static int Max(List <int> numbers)
 {
     return(HelpersMethods.FindMaxNumber(numbers));
 }
Exemplo n.º 22
0
 public AbstractWebPage(IWebDriver driver)
 {
     Driver        = driver;
     HelperMethods = new HelpersMethods(driver);
     _selectors    = new DriverSelectors(driver);
 }
Exemplo n.º 23
0
 public static int Sum(List <int> numbers)
 {
     return(HelpersMethods.CalculateSum(numbers));
 }
        internal static void Response(Section section, string name)
        {
            try
            {
                //Create list of skills
                List <string> expList         = new List <string>();
                var           skillsModelList = new List <BufferClass>();
                //Get text from tables
                for (int i = 0; i < 6; i++)
                {
                    List <string> str = HelpersMethods.GetTextFromTable(section.Tables[i]);
                    skillsModelList.AddRange(ProcessSkills.ProccSkills(str));
                    Console.WriteLine(@"Parse {0} table complete", i + 1);
                    //After reading, create json model
                }
                expList = HelpersMethods.GetTextFromTable(section.Tables[7]); // table with exp
#if NEW_PARSE_DEBUG_SKILL
                foreach (string s in skillsList)
                {
                    Console.WriteLine(s);
                }
                foreach (string s in expList)
                {
                    Console.WriteLine(s);
                }
                Console.ReadKey();
#endif
#if NEW_PARSE_DEBUG_EXP
                foreach (string s in expList)
                {
                    Console.WriteLine(s);
                }
#endif
                Console.WriteLine("Parse complete");


                var expModelList = ProcessExps.ProccExp(expList);
                expModelList.AddRange(skillsModelList);
#if NEW_PARSE_DEBUG_SKILLS_AND_EXP
                foreach (ModelSkill s in skillsModelList)
                {
                    Console.WriteLine(s.name + " " + s.level + " " + s.type + " " + s.allNames.Count.ToString());
                }
#endif
                //HelpersMethods.DeleteSimilarSkills(ref expModelList);
                //HelpersMethods.CheckLeadSkill(ref expModelList);
                string         connectionString = "mongodb://*****:*****@ds046667.mlab.com:46667/workers_db";
                MongoClient    client           = new MongoClient(connectionString);
                IMongoDatabase database         = client.GetDatabase("workers_db");
                database.CreateCollection(name);
                var colSkills = database.GetCollection <ModelSkill>(name);
                var colLevels = database.GetCollection <SkillLevel>(name + "Lvl");
                var data      = HelpersMethods.ToModelSkills(expModelList);
                colSkills.InsertMany(data.Item1.ToArray());
                colLevels.InsertMany(data.Item2.ToArray());
            }
            catch
            {
                Console.WriteLine("Invalid document");
            }
        }