Ejemplo n.º 1
0
        private void btnRemoveHotkey_Click(object sender, EventArgs e)
        {
            unsafe
            {
                HotKeyDataHolder  hkdh;
                HotKeyRemovalForm hkrf = new HotKeyRemovalForm(&hkdh, HotKeys);
                HelperFunc.CreateFormStartPosition(ref hkrf, this);

                DialogResult result = hkrf.ShowDialog();
                switch (result)
                {
                case DialogResult.OK:
                    HotKey hk = new HotKey(hkdh.id, hkdh.keyModifier, hkdh.key);
                    HotKeys.Remove(hk);
                    UnregisterHotKey(Handle, hk.id);
                    break;

                case DialogResult.Yes:
                    foreach (KeyValuePair <HotKey, ThemePathContainer> entry in HotKeys)
                    {
                        UnregisterHotKey(Handle, entry.Key.id);
                    }

                    HotKeys = new Dictionary <HotKey, ThemePathContainer>();
                    break;
                }
            }

            logStatus();
        }
Ejemplo n.º 2
0
            public async Task <UserDto> Handle(Query request, CancellationToken cancellationToken)
            {
                IdentityUser identityUser = await _unitOfWork.IdentityUserRepo.FindFirstAsync(request.UserName, cancellationToken);

                if (identityUser == null)
                {
                    throw new CustomException(HttpStatusCode.BadRequest);
                }

                //If recently expired token is matching with token in request please return recently generated token
                //This will be the case when two concurrent http request comes from same client and one request updates refresh token
                else if (request.RefreshToken == identityUser.PreviousRefreshToken && identityUser.PreviousRefreshTokenExpiry > HelperFunc.GetCurrentDateTime())
                {
                    return(_mapperHelper.Map <IdentityUser, UserDto>(identityUser));
                }

                //Check if current refresh token is matching and valid
                else if (request.RefreshToken == identityUser.RefreshToken && identityUser.RefreshTokenExpiry > HelperFunc.GetCurrentDateTime())
                {
                    //If current valid token is expired, generate new token and return it.
                    //else return existing token that is still valid.
                    if (request.RefreshToken == identityUser.RefreshToken)
                    {
                        identityUser.PreviousRefreshToken       = identityUser.RefreshToken;
                        identityUser.PreviousRefreshTokenExpiry = HelperFunc.GetCurrentDateTime().AddMinutes(_PREVIOUS_REFRESH_TOKEN_EXPIRES_IN_SEC);

                        identityUser.RefreshToken       = _jwtGenerator.CreateRefreshToken();
                        identityUser.RefreshTokenExpiry = HelperFunc.GetCurrentDateTime().AddDays(_REFRESH_TOKEN_EXPIRS_IN_DAYS);
                        _unitOfWork.IdentityUserRepo.Update(identityUser);
                        await _unitOfWork.SaveAsync(cancellationToken);
                    }
                    return(_mapperHelper.Map <IdentityUser, UserDto>(identityUser));
                }
                throw new CustomException(HttpStatusCode.BadRequest);
            }
Ejemplo n.º 3
0
        private void btnPickHotkeys_Click(object sender, EventArgs e)
        {
            unsafe
            {
                HotKeyDataHolder hkdh;
                ThemeDataHolder  tdh;
                HotKeyPickerForm hkpf = new HotKeyPickerForm(&hkdh, &tdh, HotKeys);
                HelperFunc.CreateFormStartPosition(ref hkpf, this);

                DialogResult result = hkpf.ShowDialog();

                if (result == DialogResult.OK)
                {
                    string themePathFromCSTR1 = new string(tdh.ThemePath1);
                    string themePathFromCSTR2 = new string(tdh.ThemePath2);

                    //After the form is closed we can make a new KeyValuePair for our dictionary and register the key.
                    RegisterHotKey(Handle, hkdh.id, hkdh.keyModifier, hkdh.keyHashCode);
                    HotKeys.Add(
                        HotKey.FormNewHotKey(hkdh),
                        new ThemePathContainer(themePathFromCSTR1, themePathFromCSTR2)
                        );
                }
            }

            logStatus();
        }
Ejemplo n.º 4
0
        private void logStatus()
        {
            txtStatus.Text = "";
            string desktopT = (DesktopThemePath == null) ? "Aero" : DesktopThemeName;
            string gameT    = (GameThemePath == null) ? "High Contrast White" : GameThemeName;

            //Note(Eli): Magic numbers for CreateWhiteSpace make these values line up in a monospaced font.
            log(
                "Version:" + HelperFunc.CreateWhiteSpace(7) + VERSION_NUM,
                "Is Enabled:" + HelperFunc.CreateWhiteSpace(4) + IsEnabled,
                "Boot on start:" + HelperFunc.CreateWhiteSpace(1) + BootOnStart,
                "",
                "Desktop theme:" + HelperFunc.CreateWhiteSpace(1) + desktopT,
                "In-game theme:" + HelperFunc.CreateWhiteSpace(1) + gameT,
                "\n"
                );

            log("Hotkeys<Key, Theme>:" + HelperFunc.CreateWhiteSpace(4) + "{");
            if (HotKeys != null)
            {
                foreach (KeyValuePair <HotKey, ThemePathContainer> entry in HotKeys)
                {
                    log(HelperFunc.CreateWhiteSpace(4) + "[" + entry.Key.ToString() + ", " + entry.Value.ToString() + "]");
                }
            }
            log("}");

            log(
                "",
                "Clean Logs:" + HelperFunc.CreateWhiteSpace(8) + USettings.GetOptions().Contains(Options.CLEAN_LOGS),
                "Clean Old Logs:" + HelperFunc.CreateWhiteSpace(4) + USettings.GetOptions().Contains(Options.CLEAN_LOGS_ONLY_BEFORE_TODAY),
                "Clean Fatal Logs:" + HelperFunc.CreateWhiteSpace(2) + USettings.GetOptions().Contains(Options.CLEAN_FATAL_LOGS)
                );
        }
Ejemplo n.º 5
0
        public static T FindRouteValue <T>(IHttpContextAccessor _httpContextAccessor, string routeKey)
        {
            RouteValueDictionary          routeValues    = _httpContextAccessor.HttpContext.Request.RouteValues;
            KeyValuePair <string, object> routeValuePair = routeValues.SingleOrDefault(x => HelperFunc.IsEqualString(x.Key, routeKey));

            return(HelperFunc.ChangeType <T>(routeValuePair.Value));
        }
Ejemplo n.º 6
0
        public void Update(TDomain entity)
        {
            TDomain domain = _tempRepo.First(e => string.Compare(e.UniqueIdentifier, entity.UniqueIdentifier, true) == 0);

            HelperFunc.CopyProps(entity, domain);
            _updatedEntitiesRepo.Add(domain);
        }
Ejemplo n.º 7
0
            public async Task <Guid> Handle(Command request, CancellationToken cancellationToken)
            {
                DataModel.Activity activity = _mapperHelper.Map <Command, DataModel.Activity>(request);
                //Generate new Id for new Entity
                activity.Id = Guid.NewGuid();
                _unitOfWork.ActivityRepo.Add(activity);

                UserActivity hostAttendee = new UserActivity
                {
                    Activity   = activity,
                    IsHost     = true,
                    DateJoined = HelperFunc.GetCurrentDateTime(),
                    AppUserId  = _userAccessor.GetCurrentUserId()
                };

                _unitOfWork.UserActivityRepo.Add(hostAttendee);

                int insertCnt = await _unitOfWork.SaveAsync(cancellationToken);

                if (insertCnt > 0)
                {
                    return(activity.Id);
                }

                throw new Exception("Problem saving changes to database");
            }
Ejemplo n.º 8
0
        private void btnHelp_Click(object sender, EventArgs e)
        {
            HelpUserForm.HelpForm f = new HelpUserForm.HelpForm();
            HelperFunc.CreateFormStartPosition(ref f, this);

            f.ShowDialog();
        }
Ejemplo n.º 9
0
        public void WriteConfig(List <HotKey.HotKey> HotKeys)
        {
            string programExePathFolder = HelperFunc.GetExeDirectory();

            StreamWriter sw = new StreamWriter(programExePathFolder + Constants.Constants.APP_CONFIG_LOCATION);

            try
            {
                if (HotKeys != null)
                {
                    foreach (HotKey.HotKey entry in HotKeys)
                    {
                        //TODO:
                        //sw.Write("Hotkey{ ");
                        //sw.Write(entry.Key.id + " " + entry.Key.keyModifier + " " + entry.Key.key);
                        //sw.Write(" " + entry.Value.ToAbsoluteString());
                        //sw.Write(" }\n");
                    }
                }
            }
            catch (Exception e)
            {
                //if (e is IOException)
                //    FileLogger.Log("Could not read CFG file: " + e.Message, LogOptions.DISPLAY_ERROR);
                //else
                //    FileLogger.Log("Unknown exception caught while reading config file: " + e.Message, LogOptions.SHOULD_THROW);
            }
            finally
            {
                sw.Close();
            }
        }
Ejemplo n.º 10
0
 public void TransmitAudio(List <Keys> k)
 {
     //todo: transmit audio.
     if (IS_DEBUG)
     {
         this.txtDetectedKeys.Text = HelperFunc.GenerateStringFromKeys(this.KL.KeysPressed);
     }
 }
Ejemplo n.º 11
0
        public PhotoMapper()
        {
            Map <Photo.Add.Command, DataModel.Photo>()
            .ForMember(dest => dest.ContentType, opt => opt.MapFrom(src => src.File.ContentType))
            .ForMember(dest => dest.ActualFileName, opt => opt.MapFrom(src => src.File.FileName))
            .ForMember(dest => dest.Length, opt => opt.MapFrom(src => src.File.Length))
            .ForMember(dest => dest.UploadedDate, opt => opt.MapFrom(src => HelperFunc.GetCurrentDateTime()));

            Map <DataModel.Photo, PhotoDto>(false)
            .ForMember(dest => dest.Url, opt => opt.MapFrom <PhotoUrlResolver>());
        }
Ejemplo n.º 12
0
        public CommentMapper()
        {
            Map <DataModel.Comment, CommentDto>()
            .ForMember(dest => dest.UserDisplayName, opt => opt.MapFrom(src => src.Author.DisplayName))
            .ForMember(dest => dest.UserImage, opt => opt.MapFrom <CommentPhotoUrlResolver>())
            .ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.Author.Id));

            Map <Create.Command, DataModel.Comment>(false)
            .ForMember(dest => dest.Id, opt => opt.MapFrom(src => Guid.NewGuid()))
            .ForMember(dest => dest.CreatedDate, opt => HelperFunc.GetCurrentDateTime());
        }
Ejemplo n.º 13
0
        public static void CleanLogsFolder(params UserSettingsEnum.Options[] lOptions)
        {
            string logDirectory = GetLogDirectory();

            string[] files = Directory.GetFiles(logDirectory);

            bool cleanupThrownLogs  = lOptions.Contains(UserSettingsEnum.Options.CLEAN_FATAL_LOGS);
            bool cleanupBasedOnDate = lOptions.Contains(UserSettingsEnum.Options.CLEAN_LOGS_ONLY_BEFORE_TODAY);

            string[] logsBeforeToday = FindAllLogsCreatedBefore(DateTime.Today);

            foreach (string file in files)
            {
                bool   fileMarkedForDeletion = false;
                string ext = HelperFunc.GetFileExtension(file);

                if (ext != NORMAL_LOG_EXT && ext != THROWN_LOG_EXT)
                {
                    continue;
                }

                //TODO(Medium): Fix this copy paste job. It works but the fact Im copy pasting code is bad news.
                if (cleanupBasedOnDate && logsBeforeToday.Contains(file))
                {
                    if (cleanupThrownLogs)
                    {
                        fileMarkedForDeletion = true;
                    }
                    else
                    if (ext != THROWN_LOG_EXT)
                    {
                        fileMarkedForDeletion = true;
                    }
                }
                else
                {
                    if (cleanupThrownLogs)
                    {
                        fileMarkedForDeletion = true;
                    }
                    else
                    if (ext != THROWN_LOG_EXT)
                    {
                        fileMarkedForDeletion = true;
                    }
                }

                if (fileMarkedForDeletion)
                {
                    File.Delete(file);
                }
            }
        }
Ejemplo n.º 14
0
        private void WriteConfig()
        {
            string programExePathFolder = GetExeDirectory();

            StreamWriter sw = new StreamWriter(programExePathFolder + Constants.APP_CONFIG_LOCATION);

            try
            {
                sw.WriteLine("//Note to those reading:\n//Modifying this file could result in the breaking of your config.\n");
                sw.WriteLine(nameof(IsEnabled) + HelperFunc.CreateWhiteSpace(1) + "\"" + IsEnabled.ToString() + "\"");

                foreach (Options o in USettings.GetOptions())
                {
                    sw.WriteLine(o.ToString() + HelperFunc.CreateWhiteSpace(1) + "\"True\"");
                }

                if (DesktopThemePath != null)
                {
                    sw.WriteLine(nameof(DesktopThemePath) + HelperFunc.CreateWhiteSpace(1) + "\"" + DesktopThemePath + "\"");
                }
                if (GameThemePath != null)
                {
                    sw.WriteLine(nameof(GameThemePath) + HelperFunc.CreateWhiteSpace(1) + "\"" + GameThemePath + "\"");
                }

                if (HotKeys != null)
                {
                    foreach (KeyValuePair <HotKey, ThemePathContainer> entry in HotKeys)
                    {
                        sw.Write("Hotkey{ ");
                        sw.Write(entry.Key.id + " " + entry.Key.keyModifier + " " + entry.Key.key);
                        sw.Write(" " + entry.Value.ToAbsoluteString());
                        sw.Write(" }\n");
                    }
                }
            }
            catch (Exception e)
            {
                if (e is IOException)
                {
                    FileLogger.Log("Could not read CFG file: " + e.Message, LogOptions.DISPLAY_ERROR);
                }
                else
                {
                    FileLogger.Log("Unknown exception caught while reading config file: " + e.Message, LogOptions.SHOULD_THROW);
                }
            }
            finally
            {
                sw.Close();
            }
        }
Ejemplo n.º 15
0
            public IdentityUser Resolve(Register.Command source, AppUser dest, IdentityUser destMember, ResolutionContext context)
            {
                string salt = _cryptoHelper.CreateBase64Salt();

                return(new IdentityUser
                {
                    UserName = source.UserName,
                    Salt = salt,
                    Passoword = _cryptoHelper.GenerateHash(source.Password, salt),
                    RefreshToken = _jwtGenerator.CreateRefreshToken(),
                    RefreshTokenExpiry = HelperFunc.GetCurrentDateTime().AddDays(30)
                });
            }
Ejemplo n.º 16
0
    DetectResult BrickDetect(Transform trans)
    {
        DetectResult detectResult = new DetectResult();
        RaycastHit   hit;

        //Debug.Log("yeah");
        if (Physics.Raycast(trans.position, trans.forward, out hit, Mathf.Infinity, layerMask))
        {
            //Debug.Log("point: " + hit.point);
            //Debug.Log("normal" + hit.normal);

            //if(hit.normal.x != (int)(hit.normal.x) || hit.normal.y != (int)(hit.normal.y) || hit.normal.z != (int)(hit.normal.z)){
            if (!HelperFunc.Equal(hit.normal.x, (int)(hit.normal.x)) || !HelperFunc.Equal(hit.normal.y, (int)(hit.normal.y)) || !HelperFunc.Equal(hit.normal.z, (int)(hit.normal.z)))
            {
                //Debug.Log("normalCheckFailed");
                detectResult.point      = new Vector3Int(0, 0, 0);
                detectResult.detectable = false;
                return(detectResult);
            }
            else
            {
                //Debug.Log("normal check ok");
                setPoint = Hitpoint2Grid(hit.point, hit.normal);
                //Debug.Log(setPoint);
                intersectingCols = Physics.OverlapSphere(setPoint, 0.01f);
                if (intersectingCols.Length == 0)
                {
                    Debug.DrawLine(transform.position, setPoint, Color.red);
                    detectResult.point      = setPoint;
                    detectResult.detectable = true;
                    return(detectResult);
                }
                else
                {
                    detectResult.point      = new Vector3Int(0, 0, 0);
                    detectResult.detectable = false;
                    return(detectResult);
                }
            }
            //return true;
        }
        else
        {
            detectResult.point      = new Vector3Int(0, 0, 0);
            detectResult.detectable = false;
            return(detectResult);
            //return false;
        }
    }
Ejemplo n.º 17
0
        private void btnOpenAdvanced_Click(object sender, EventArgs e)
        {
            AdvancedUserSettingsForm f = new AdvancedUserSettingsForm(USettings.GetOptions());

            HelperFunc.CreateFormStartPosition(ref f, this);

            DialogResult result = f.ShowDialog();

            if (result == DialogResult.OK)
            {
                USettings = f.USettingsOptions;
            }

            logStatus();
        }
        private double[][] RandomizeWeights(double[][] weights)
        {
            double[][] newWeights = new double[weights.Length][];

            for (var i = 0; i < weights.Length; i++)
            {
                double[] weightLayer = new double[weights[i].Length];

                for (int j = 0; j < weightLayer.Length; j++)
                {
                    weightLayer[j] = HelperFunc.RandomWeight();
                }

                newWeights[i] = weightLayer;
            }

            return(newWeights);
        }
Ejemplo n.º 19
0
        private void btnPickHotKey_Click(object sender, EventArgs e)
        {
            PickHotKeyDialog phkd = new PickHotKeyDialog();

            HelperFunc.CreateFormStartPosition(ref phkd, this);

            DialogResult result = phkd.ShowDialog();

            if (result != DialogResult.OK)
            {
                return;
            }

            HKKey    = phkd.Key;
            HKKeyMod = phkd.KeyMod;

            lblKeyOK.Text      = @"Finished";
            lblKeyOK.ForeColor = Color.Green;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Asserts that there are no files with the given extension in a folder.
        /// </summary>
        /// <param name="extension">Extension to check.</param>
        /// <param name="folder">Folder to find files in.</param>
        /// <returns>True if there are no files with the given extension otherwise false or a throw if there are files with the extension.</returns>
        public static bool NoFilesWithExtension(string extension, string folder)
        {
            string[] files = Directory.GetFiles(folder);

            foreach (string file in files)
            {
                if (HelperFunc.GetFileExtension(file) == extension)
                {
                    if (IsStrict)
                    {
                        throw new AssertionFailedException("File found containing extension " + extension + ", file: " + file);
                    }

                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 21
0
            public async Task <Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                UserActivity hostAttendee = new UserActivity
                {
                    ActivityId = request.ActivityId,
                    DateJoined = HelperFunc.GetCurrentDateTime(),
                    AppUserId  = _userAccessor.GetCurrentUserId()
                };

                _unitOfWork.UserActivityRepo.Add(hostAttendee);

                int insertCnt = await _unitOfWork.SaveAsync(cancellationToken);

                if (insertCnt > 0)
                {
                    return(Unit.Value);
                }

                throw new Exception("Problem saving changes to database");
            }
Ejemplo n.º 22
0
            public async Task <UserDto> Handle(Command request, CancellationToken cancellationToken)
            {
                IdentityUser identityUser = await _unitOfWork.IdentityUserRepo.FindFirstAsync(request.UserName, cancellationToken);

                if (identityUser == null)
                {
                    throw new CustomException(HttpStatusCode.Unauthorized);
                }

                if (_cryptoHelper.GenerateHash(request.Password, identityUser.Salt) == identityUser.Passoword)
                {
                    identityUser.PreviousRefreshToken       = null;
                    identityUser.PreviousRefreshTokenExpiry = null;
                    identityUser.RefreshToken       = _jwtGenerator.CreateRefreshToken();
                    identityUser.RefreshTokenExpiry = HelperFunc.GetCurrentDateTime().AddDays(30);
                    _unitOfWork.IdentityUserRepo.Update(identityUser);

                    await _unitOfWork.SaveAsync(cancellationToken);

                    return(_mapperHelper.Map <IdentityUser, UserDto>(identityUser));
                }
                throw new CustomException(HttpStatusCode.Unauthorized);
            }
    private void Statistics(string timeCounterText, string genCounterText)
    {
        firstStatistics = SimulationManagerScript.Instance.firstStatistics;
        float time = HelperFunc.ParseTimeFromGUI(timeCounterText);

        if (firstStatistics)
        {
            SimulationManagerScript.Instance.firstStatistics = false;
            string[] currentRunInfo = SimulationManagerScript.Instance.GetCurrentRunInfo();
            string   stringInfo     = "\nNEW DATA\n";
            foreach (var stringData in currentRunInfo)
            {
                stringInfo += stringData + "\n";
            }
            stringInfo += timeCounterText + "\n" + genCounterText + "\n";
            File.AppendAllText(pathToStatisticsFile, stringInfo);
        }

        if (time < gui.GetCurrentBestTime())
        {
            File.AppendAllText(pathToStatisticsFile, timeCounterText + "\t" + genCounterText + "\n");
            gui.SetCurrentBestTime(time);
        }
    }
Ejemplo n.º 24
0
        public static string[] FindAllLogsCreatedBefore(DateTime time)
        {
            string[] allFiles = Directory.GetFiles(GetLogDirectory());

            /*
             * foreach (string file in allFiles)
             * {
             *  string dateTimeStringWithExtension = file.Substring(file.LastIndexOf("_", StringComparison.Ordinal));
             *  string dateTimeString = dateTimeStringWithExtension.Remove(dateTimeStringWithExtension.LastIndexOf(".", StringComparison.Ordinal));
             *
             *  Int64 ticks = Convert.ToDateTime(dateTimeString).Ticks;
             *  if (ticks < time.Ticks)
             *      filesBeforeDate.Add(file);
             * }
             * return filesBeforeDate.ToArray();
             *
             * //Note(Eli): The LINQ below used to be this. Im leaving the LINQ in simply because I'm amazed Resharper came up with it even though its barely readable.
             */

            return((from file in allFiles
                    let dateTimeStringWithExtension = file.Substring(file.LastIndexOf("_", StringComparison.Ordinal) + 1)
                                                      let dateTimeString = dateTimeStringWithExtension
                                                                           .Remove(dateTimeStringWithExtension
                                                                                   .LastIndexOf(".", StringComparison.Ordinal))
                                                                           let ticks = HelperFunc.TryConvertToDateTime(dateTimeString).Ticks
                                                                                       where ticks < time.Ticks select file).ToArray());
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Returns a shorthand string representation of the contents held within this instance.
 /// </summary>
 /// <returns>A shorthand string representation of the contents held within this instance.</returns>
 public override string ToString()
 {
     return(HelperFunc.CreateShortHandTheme(Themes[0]) + ((Themes[1] == string.Empty || Themes[1] == null) ? "" : " " + HelperFunc.CreateShortHandTheme(Themes[1])));
 }
Ejemplo n.º 26
0
 public float GetCurrentBestTime()
 {
     return(HelperFunc.ParseTimeFromGUI(BestTime.text));
 }
 public Synapse(Neuron inputNeuron, Neuron outputNeuron)
 {
     InputNeuron  = inputNeuron;
     OutputNeuron = outputNeuron;
     Weight       = HelperFunc.RandomWeight();
 }
Ejemplo n.º 28
0
 public void RotateBrick(ChangeType ct)
 {
     transform.Rotate(HelperFunc.GetDirVector(ct));
 }