示例#1
0
        public void RatingTest()
        {
            var optionsBuilder = new DbContextOptionsBuilder <IGContext>();

            optionsBuilder.UseInMemoryDatabase("IELTS_GiaSu");
            var dbContext = new IGContext(optionsBuilder.Options);
            var dateTime  = DateTime.UtcNow;
            var ratingObj = new IG_Rating_Login_Service
            {
                feedback    = "Hệ thống tốt",
                loginToken  = MD5Generator.CreateMD5(dateTime.ToString()),
                timestamp   = dateTime,
                serviceCode = "IG_VeSinh",
                ratingPoint = 5
            };

            dbContext.IG_Rating_Login_Service.Add(ratingObj);
            var result = dbContext.SaveChanges();

            if (result > 0)
            {
                Assert.Pass();
            }
            else
            {
                Assert.Fail();
            }
        }
示例#2
0
        private List <ISSStationItem> GetStationsFromApi()
        {
            var client  = new RestClient(_configService.Custom["iss_system_url"]);
            var request = new RestRequest(ISSAdditionalDataEnum.station.ToString(), Method.POST);

            var cmpId         = _configService.Custom["iss_system_cmp_id"];
            var cmpHash       = _configService.Custom["iss_system_cmp_hash"];
            var currentTime   = DateTime.Now.ToString("yyyyMMddHHmmss");
            var calculateHash = MD5Generator.CalculateMD5Hash(cmpId, currentTime, cmpHash);

            request.AddParameter("cmp_id", cmpId);
            request.AddParameter("datetime", currentTime);
            request.AddParameter("hash", calculateHash);
            var response = client.Execute(request);

            return(response.Content
                   .Split('\n')
                   .Select(s =>
            {
                var split = s.Split('|');
                return new ISSStationItem
                {
                    stationId = int.Parse(split[0]),
                    value = split[1],
                };
            })
                   .ToList());
        }
示例#3
0
        public bool QuickDeepCompare(object item1, object item2)
        {
            var item1Bytes = ObjectSerializer.ToBytes(item1);
            var item2Bytes = ObjectSerializer.ToBytes(item2);

            return(MD5Generator.Generate(item1Bytes) == MD5Generator.Generate(item2Bytes));
        }
示例#4
0
        //Data Acquire
        //data validation
        public UserEntity CheckUserInfo(string userName, string pwd)
        {
            try
            {
                if (DBConnection())
                {
                    string userSql = "select * from users where user_name=@user_name and password=@pwd and is_validation=1";
                    adapter = new SqlDataAdapter(userSql, conn);
                    adapter.SelectCommand.Parameters.Add(
                        new SqlParameter("@user_name",
                                         SqlDbType.VarChar)
                    {
                        Value = userName
                    });
                    adapter.SelectCommand.Parameters.Add(
                        new SqlParameter("@pwd",
                                         SqlDbType.VarChar)
                    {
                        Value = MD5Generator.GetMD5String(pwd + "@" + userName)
                    });

                    DataTable table   = new DataTable();
                    int       counter = adapter.Fill(table);

                    if (counter <= 0)
                    {
                        throw new Exception("User name or password is wrong!");
                    }
                    DataRow dr = table.Rows[0];
                    if (dr.Field <Int32>("is_can_login") == 0)
                    {
                        throw new Exception("Unauthorized User!");
                    }
                    UserEntity userInfo = new UserEntity();
                    userInfo.UserName = dr.Field <string>("user_name");
                    userInfo.RealName = dr.Field <string>("real_name");
                    //password needs MD5
                    userInfo.PassWord = dr.Field <string>("password");
                    userInfo.Avatar   = dr.Field <string>("avatar");
                    userInfo.Gender   = dr.Field <Int32>("gender");
                    return(userInfo);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                this.Dispose();
            }
            return(null);
        }
示例#5
0
        public async Task <LoginUserResponse> ChangePassword([FromBody] ApplicationUserDTO data)
        {
            LoginUserResponse resp = new LoginUserResponse();

            resp.IsSuccess = false;
            try
            {
                ApplicationUser.ChangePassword(data.LoginName, MD5Generator.ToMD5Hash(data.Password));
                resp.IsSuccess = true;
            }
            catch (Exception e)
            {
            }

            return(resp);
        }
示例#6
0
        public async Task <string> GetGravatarImage(string email)
        {
            try {
                var hash        = MD5Generator.CalculateMD5Hash(email.ToLower().Trim());
                var gravatarUri = new Uri($"/avatar/{hash}?d=404", UriKind.Relative);
                var res         = await _client.GetAsync(gravatarUri);

                res.EnsureSuccessStatusCode();
                return(new Uri(_client.BaseAddress, $"/avatar/{hash}").AbsoluteUri);
            }
            catch (Exception ex) {
                _logger.LogError($"Error obtaining gravatar image\n\t{ex.Message}");
            }

            return(string.Empty);
        }
示例#7
0
        // Call web api function to upload file from the client
        internal static void UploadFileAsync(FileInfo fileInfo, bool isPublic, CUserInfo userInfo)
        {
            byte[]    hash      = MD5Generator.MD5Hash(fileInfo.FullName);
            CFileInfo cFileInfo = new CFileInfo(
                Guid.Empty, fileInfo.Name, fileInfo.FullName, fileInfo.Length, userInfo.Id, isPublic, hash, DateTime.Now, 0, 0, 0);
            HttpResponseMessage response = filesWebApi.UploadFileAsync(cFileInfo, userInfo).Result;

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine($"File {cFileInfo.Name} has been successfully uploaded to MediaServer!");
            }
            else
            {
                Console.WriteLine($"File {cFileInfo.Name} couldn't be uploaded to MediaServer! " +
                                  $"Response content:{response.ReasonPhrase}");
            }
        }
示例#8
0
        public ApplicationUserDTO Post([FromBody] UserAccessMappingRequest data)
        {
            ApplicationUser current = ApplicationUser.NewApplicationUser();

            data.User.UpdatedBy = CurrentUserID;
            current.CustomSave(data, MD5Generator.ToMD5Hash(data.User.Password));
            var userDto = ApplicationUser.GetByApplicationUserID(current.ApplicationUserID).CurrentDTO;

            if (data.IsFinAdmin && data.User.ApplicationUserID <= 0)
            {
                FinAdministrator fad;
                DateTime         CurrentTime = DateTime.Now;

                if (data.FinAdminId <= 0)
                {
                    fad                = FinAdministrator.NewFinAdministrator();
                    fad.CreatedOn      = CurrentTime;
                    fad.CreatedBy      = CurrentUserID;
                    fad.IsActive       = true;
                    fad.AddressID      = userDto.PhysicalAddressID;
                    fad.Name           = $"{data.User.FirstName} {data.User.LastName} {userDto.ApplicationUserID}";
                    fad.IsOrganisation = false;
                    fad.Email          = data.User.EmailAddress;
                }
                else
                {
                    fad = FinAdministrator.GetByFinAdministratorID(data.FinAdminId);
                }

                var finUsers = FinAdministratorAppUser.NewFinAdministratorAppUser();
                finUsers.FinAdministratorID = fad.FinAdministratorID;
                finUsers.ApplicationUserId  = userDto.ApplicationUserID;
                finUsers.CreatedOn          = CurrentTime;
                finUsers.CreatedBy          = CurrentUserID;
                finUsers.IsActive           = true;

                fad.FinAdministratorAppUsers.Add(finUsers);
                fad.Save();
            }

            return(userDto);
        }
        public async Task <IActionResult> Login(string serviceCode, string passcode)
        {
            var getService = await unitOfWork.IG_ServiceRepository.Get_IG_Service(serviceCode, passcode);

            if (getService != null)
            {
                var loginService = new IG_Login_Service
                {
                    serviceCode = serviceCode,
                    timestamp   = DateTime.UtcNow,
                };
                loginService.loginToken = MD5Generator.CreateMD5(loginService.timestamp.ToString());
                unitOfWork.IG_Login_ServiceRepository.Add(loginService);
                unitOfWork.Save();
                HttpContext.Session.SetString(Constant_Login.LOGINTOKEN, loginService.loginToken);
                HttpContext.Session.SetString(Constant_Login.SERVICE, loginService.serviceCode);
                return(Ok(getService));
            }
            return(NotFound());
        }
示例#10
0
        public async Task <LoginUserResponse> Post([FromBody] ApplicationUserDTO data)
        {
            LoginUserResponse resp = new LoginUserResponse();

            resp.IsSuccess = false;
            try
            {
                ApplicationUser user = ApplicationUser.LoginUser(data.LoginName, MD5Generator.ToMD5Hash(data.Password));
                if (user != null)
                {
                    resp = await SigninUser(user.LoginName);

                    resp.MustChangePassword  = user.MustChangePassword;
                    resp.ForceChangePassword = user.ForceChangePassword;
                }
            }
            catch (Exception e)
            {
            }

            return(resp);
        }
示例#11
0
        public void GetAnswerKeyToRedirectToBuyTicket(ref SearchTicketFormView model)
        {
            var client  = new RestClient(_configService.Custom["iss_system_url"]);
            var request = new RestRequest(string.Format("redir/{0}", ISSFormTypeEnum.single), Method.POST);

            var cmpId   = _configService.Custom["iss_system_cmp_id"]; //identyfikator firmy
            var cmpHash = _configService.Custom["iss_system_cmp_hash"];

            var dateFrom = model.Date.HasValue ? model.Date.Value.ToString("yyyy-MM-dd") : string.Empty; //data początkowego przejazdu

            var times = model.Time.HasValue ? model.Time.Value.ToString("HH:mm") : string.Empty;         //czasy początkowych odjazdów dla każdego odcinka, oddzielone przecinkami

            var stations = string.Join(",",
                                       GetStationId(model.StartStation),
                                       GetStationId(model
                                                    .EndStation)); //lista identyfikatorów stacji, oddzielonych przecinkami. Zawsze będzie co najmniej stacja początkowa i końcowa.

            var sectionCount = "1";                                //liczba odcinków. Zawsze co najmniej 1.

            var calculateHash =
                MD5Generator.CalculateMD5Hash(cmpId, cmpHash, dateFrom, sectionCount, times,
                                              stations); //hash potwierdzający, że dane są rzeczywiście od podanej wyżej firmy

            request.AddParameter("cmp_id", cmpId);
            request.AddParameter("hash", calculateHash);
            request.AddParameter("kind_stid",
                                 "2"); //opcjonalny, ale zaleca się zawsze używać) – Typ identyfikatora stacji. Jeśli wartością jest 0 lub nie podano parametru, używa wartości domyślnej (hafas).
            request.AddParameter("stations", stations);
            request.AddParameter("section_count", sectionCount);
            request.AddParameter("date_from", dateFrom);
            request.AddParameter("times", times);

            model.AnswerKeyResponse = new ISSResponseModel(client.Execute(request).Content);

            if (!model.AnswerKeyResponse.IsError)
            {
                model.PolRegioRedirectUrl = string.Format("{0}redir?answer_key={1}", _configService.Custom["iss_system_url"], model.AnswerKeyResponse.ResponseMessage);
            }
        }
        protected static string HashCredentials(IDictionary requestInfo, DigestCredential credential)
        {
            string str5;

            if (requestInfo == null)
            {
                throw new ArgumentNullException("requestInfo");
            }
            string       s         = string.Format("{0}:{1}:{2}", credential.Name, requestInfo["realm"], credential.Password);
            string       str2      = string.Format("AUTHENTICATE:{1}", requestInfo.Contains("uri") ? requestInfo["uri"].ToString() : string.Empty);
            MD5Generator generator = new MD5Generator();

            generator.Initialize();
            generator.Update(Encoding.ASCII.GetBytes(s));
            byte[] hash = generator.Hash;
            s = string.Format("{0}:{1}", requestInfo["nonce"], requestInfo["cnonce"]);
            generator.Initialize();
            generator.Update(hash);
            generator.Update(Encoding.ASCII.GetBytes(s));
            string str3 = StringUtil.BytesToHex(generator.Hash);

            generator.Initialize();
            generator.Update(Encoding.ASCII.GetBytes(str2));
            string str4 = StringUtil.BytesToHex(generator.Hash);

            if (requestInfo.Contains("qop"))
            {
                str5 = string.Format("{0}:{1}:{2}:{3}:{4}:{5}", new object[] { str3, requestInfo["nonce"], requestInfo["nc"], requestInfo["cnonce"], requestInfo["qop"], str4 });
            }
            else
            {
                str5 = string.Format("{0}:{1}:{2}", str3, requestInfo["nonce"], str4);
            }
            generator.Initialize();
            generator.Update(Encoding.ASCII.GetBytes(str5));
            return(StringUtil.BytesToHex(generator.Hash));
        }
示例#13
0
        public async Task <LoginUserResponse> UpdatePassword([FromBody] ApplicationUserDTO data)
        {
            LoginUserResponse resp = new LoginUserResponse();

            resp.IsSuccess = false;
            try
            {
                ApplicationUser u = ApplicationUser.UpdatePassword(HttpContext.User.Identity.Name, MD5Generator.ToMD5Hash(data.CurrentPassword), MD5Generator.ToMD5Hash(data.Password));

                resp.IsSuccess = u.ApplicationUserID != 0;
            }
            catch (Exception e)
            {
            }

            return(resp);
        }
示例#14
0
 //Quick access to the copied MD5 tool.
 string GetMD5(string strInputPath)
 {
     return(MD5Generator.GetMD5(strInputPath));
 }
示例#15
0
        // Call web api function to upload file in small chunks (to overcome 2GB limit on IIS)
        internal static async void UploadFileInChunksAsync(FileInfo fileInfo, bool isPublic, CUserInfo userInfo, CancellationToken ct)
        {
            try
            {
                // response from Media SErver
                string responseMsg = "";

                // generate hash of the file
                // todo: make it multithreaded
                Console.WriteLine("Calculating file hash...");
                byte[] hash = MD5Generator.MD5Hash(fileInfo.FullName);
                Console.WriteLine($"{fileInfo.Name} hash = {BitConverter.ToString(hash)}");


                // set DTO values
                CFileInfo cFileInfo = new CFileInfo(
                    Guid.Empty, fileInfo.Name, "", fileInfo.Length, userInfo.Id, isPublic, hash, DateTime.Now, 0, 0, 0);

                // get loadIndex from server (if file was not loaded completely. If new file size==0)
                CFileInfo fileInfoFromMediaServer = filesWebApi.FileDetails(cFileInfo, userInfo).Result;
                Int64     loadIndex = fileInfoFromMediaServer.Size;

                if (loadIndex >= fileInfo.Length)
                {
                    Console.WriteLine("This file is fully uploaded");
                    return;
                }

                // how much bytes to send to server each time
                Int32 chunkSize = UserSettings.ChunkSize;

                FileStream fs = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read, chunkSize);
                using (fs)
                {
                    // set cursor of the filestream to the loadIndex
                    fs.Seek(loadIndex, SeekOrigin.Begin);

                    HttpResponseMessage response = new HttpResponseMessage();
                    response.StatusCode = System.Net.HttpStatusCode.OK;

                    Boolean isLastChunk = false;
                    byte[]  chunk;

                    // read file to the end and send it to server in chunks
                    while (fs.Position < fs.Length & response.IsSuccessStatusCode)
                    {
                        Int64 remaining = fs.Length - fs.Position;
                        if (remaining <= chunkSize)
                        {
                            isLastChunk = true;
                            chunk       = new byte[remaining];
                        }
                        else
                        {
                            chunk = new byte[chunkSize];
                        }

                        Int32 readBytes = await fs.ReadAsync(chunk, 0, chunk.Length);

                        // if chunk is uploaded successfully - server returns 'OK'
                        response    = filesWebApi.UploadChunkAsync(cFileInfo, userInfo, chunk, isLastChunk).Result;
                        responseMsg = response.Content.ReadAsStringAsync().Result;
                        double percentage = ((double)fs.Position / (double)fs.Length) * 100;
                        Console.Write($"\rUpload progress: {percentage:0.##}%");
                    }
                }
                Console.WriteLine(responseMsg);
            }
            catch (Exception ex)
            {
                throw new FileUploadException($"Could not upload file {fileInfo.Name} to MediaServer!", ex);
            }
        }