Exemplo n.º 1
0
        public string CreateTinyUrl(string originalUrl)
        {
            // Check in the system for lonuRL CREATION
            string checkSum = MD5Hash.CalculateMD5Hash(originalUrl);

            if (_storage.ExistInHash(Constants.LongToShortUrlTable, checkSum))
            {
                _storage.GetValueFromHash(Constants.LongToShortUrlTable, checkSum);
            }

            string currentId = _storage.GetValueFromHash
                                   (Constants.CurrentIdTable, Constants.CurrentId);

            ulong  id         = ulong.Parse(currentId);
            string shortenurl = _conversion.Encode(id);

            _storage.AddValueToHash(Constants.LongToShortUrlTable, checkSum, shortenurl);

            // Create a map of shortenUrl id to original url
            _storage.AddValueToHash(Constants.UrlTable, currentId, originalUrl);

            // Increment the id by 1
            ulong next = id + (ulong)1;

            // update the current id table
            _storage.UpdateValueToHash(Constants.CurrentIdTable, Constants.CurrentId, next.ToString());

            return(shortenurl);
        }
        public BalanceDialogViewModel(Balansovie_schyotModel info)
        {
            BalanceInfo = info;

            _backup._BallnceAccount = info.BallnceAccount;
            _backup._name           = info.Name;
            _backup._active         = info.Active;

            Save = ReactiveCommand.Create(() =>
            {
                _backup._BallnceAccount = info.BallnceAccount;
                _backup._name           = info.Name;
                _backup._active         = info.Active;

                App.Current.Windows.Cast <Window>().Where(win => win is BalanceEditDialog).FirstOrDefault().Close();


                IContext con = new Context();

                XmlDocument xmlDoc = new XmlDocument();
                XmlElement request = xmlDoc.CreateElement("request");
                XmlElement q       = xmlDoc.CreateElement("q");
                q.InnerText        = "103";
                request.AppendChild(q);
                XmlElement token = xmlDoc.CreateElement("token");
                token.InnerText  = MainWindowViewModel._currentUser.Token;
                request.AppendChild(token);
                XmlElement log = xmlDoc.CreateElement("login");
                log.InnerText  = MainWindowViewModel._currentUser.Login;
                request.AppendChild(log);
                XmlElement pass = xmlDoc.CreateElement("pass");
                pass.InnerText  = MainWindowViewModel._currentUser.Password;
                request.AppendChild(pass);
                XmlElement hard = xmlDoc.CreateElement("hard");
                hard.InnerText  = MD5Hash.CalculateMD5Hash(SerialNumber.HddSerialNumber() + SerialNumber.GpuSerialNumber());
                request.AppendChild(hard);
                XmlElement sign = xmlDoc.CreateElement("sign");
                sign.InnerText  = MD5Hash.CalculateMD5Hash(103 + MD5Hash.CalculateMD5Hash(SerialNumber.HddSerialNumber() + SerialNumber.GpuSerialNumber()) + MainWindowViewModel._currentUser.Password);
                request.AppendChild(sign);
                XmlElement sifr = xmlDoc.CreateElement("sifr");
                sifr.InnerText  = BalanceInfo.BallnceAccount.ToString();
                request.AppendChild(sifr);
                XmlElement name = xmlDoc.CreateElement("name");
                name.InnerText  = BalanceInfo.Name;
                request.AppendChild(name);
                XmlElement vid = xmlDoc.CreateElement("vid");
                vid.InnerText  = BalanceInfo.Active.ToString();
                request.AppendChild(vid);
                xmlDoc.AppendChild(request);

                con.SendMessage(xmlDoc);
            });

            Cancel = ReactiveCommand.Create(() => {
                BalanceInfo.BallnceAccount = _backup._BallnceAccount;
                BalanceInfo.Name           = _backup._name;
                BalanceInfo.Active         = _backup._active;
                App.Current.Windows.Cast <Window>().Where(win => win is BalanceEditDialog).FirstOrDefault().Close();
            });
        }
Exemplo n.º 3
0
        public void InsertUserMultTasks()
        {
            // Removing users
            this.client.Delete(101, 102);

            Dictionary <int, User> insertedList = new Dictionary <int, User>();

            insertedList.Add(101, new User
            {
                UserCode    = 101,
                UserCodRef  = 2333953423432,
                UserName    = "******",
                InputDate   = DateTime.Now,
                PasswordMd5 = MD5Hash.CalculateMD5Hash("anything"),
                Status      = StatusUser.Guest,
            });

            insertedList.Add(102, new User
            {
                UserCode    = 102,
                UserName    = "******",
                InputDate   = DateTime.Now,
                PasswordMd5 = MD5Hash.CalculateMD5Hash("anything-else"),
                Status      = StatusUser.Admin,
            });


            foreach (User user in insertedList.Values)
            {
                Assert.True(this.client.Insert(user));
            }


            List <Task> tasks = new List <Task>();

            for (int i = 0; i < 4; i++)
            {
                tasks.Add(Task.Run(() => this.client.ListAll()));
            }

            List <User> users = this.client.ListAll();

            Task.WaitAll(tasks.ToArray());
            Assert.NotNull(users);
            Assert.True(users.Count > 1);

            foreach (int cod in insertedList.Keys)
            {
                User user = users.Find(delegate(User u) { return(u.UserCode == cod); });
                AssertExt.UsersTheSame(user, insertedList[cod]);
            }

            foreach (int cod in insertedList.Keys)
            {
                Assert.True(this.client.Delete(cod));
            }
        }
Exemplo n.º 4
0
        public void InsertUserWithCodRefTest()
        {
            // Removing users
            this.client.Delete(21, 22, 23);

            Dictionary <int, User> insertedList = new Dictionary <int, User>();

            insertedList.Add(21, new User
            {
                UserCode    = 21,
                UserCodRef  = 2333953423432,
                UserName    = "******",
                InputDate   = DateTime.Now,
                PasswordMd5 = MD5Hash.CalculateMD5Hash("anything"),
                Status      = StatusUser.Guest,
            });

            insertedList.Add(22, new User
            {
                UserCode    = 22,
                UserName    = "******",
                InputDate   = DateTime.Now,
                PasswordMd5 = MD5Hash.CalculateMD5Hash("anything-else"),
                Status      = StatusUser.Admin,
            });

            insertedList.Add(23, new User
            {
                UserCode    = 23,
                UserName    = "******",
                InputDate   = DateTime.Now,
                PasswordMd5 = MD5Hash.CalculateMD5Hash("otherthing"),
                Status      = StatusUser.User,
            });


            foreach (User user in insertedList.Values)
            {
                Assert.True(this.client.Insert(user));
            }

            List <User> users = this.client.ListAll();

            Assert.NotNull(users);
            Assert.True(users.Count > 2);

            foreach (int cod in insertedList.Keys)
            {
                User user = users.Find(delegate(User u) { return(u.UserCode == cod); });
                AssertExt.UsersTheSame(user, insertedList[cod]);
            }

            foreach (int cod in insertedList.Keys)
            {
                Assert.True(this.client.Delete(cod));
            }
        }
Exemplo n.º 5
0
        public void ForgottenPasswordEmailForBenutzer(string Mail)
        {
            var benutzer = BenutzerRepository.SearchUserByEMail(Mail);

            benutzer.PasswordVerificationCode = MD5Hash.CalculateMD5Hash(benutzer.BenutzerId + benutzer.Mail + benutzer.Nachname + benutzer.Vorname + benutzer.Passwort);
            benutzer.PasswortZeitstempel      = DateTime.Now;
            BenutzerRepository.EditUser(benutzer);
            MailService.SendForgottenPasswordMail(benutzer.PasswordVerificationCode, benutzer.Mail, benutzer.BenutzerId.ToString());
        }
Exemplo n.º 6
0
        /// <summary>
        /// Login method, calling the methonds that read from server
        /// </summary>
        private async void Login()
        {
            //create worker for background job
            CreateWorker();
            _semaphoreSlime = new SemaphoreSlim(1);
            isErrorAccure   = false;

            string email    = emailTxt.Text;
            string password = MD5Hash.CalculateMD5Hash(passwordTxt.Password);

            isSavingConfig = SaveConfig.IsChecked.Value;

            //************
            //todo - remove
            watch = new Stopwatch();
            watch.Start();
            //************

            //retrive the user id
            int userIdExist = await LoginUserForId(email, password);

            switch (userIdExist)
            {
            case 0:    //in case that email or password are wrong
                //print error to error label
                errorMessegeFromServer.Content    = "Error in username or password";
                errorMessegeFromServer.Visibility = Visibility.Visible;
                break;

            case 1:     //if there is a user id
                //Save login screen and change to splash
                loginScreen  = this.Content;
                this.Content = splash;
                splash.MessageTimer.Start();

                //start download data
                worker.RunWorkerAsync();
                break;

            case 2:
                //error connection
                errorMessegeFromServer.Content    = "Check your connection";
                errorMessegeFromServer.Visibility = Visibility.Visible;
                break;
            }
        }
Exemplo n.º 7
0
        public void AddBenutzer(Benutzer benutzer, string gruppe)
        {
            benutzer.BenutzerGruppen = new List <BenutzerGruppe>()
            {
                BenutzerGruppeService.SearchGroupByBezeichnung(gruppe)
            };
            benutzer.IstEmailVerifiziert = true;
            benutzer.PasswortZeitstempel = DateTime.Now;

            BenutzerRepository.AddUser(benutzer);

            benutzer = BenutzerRepository.SearchUserByEMail(benutzer.Mail);
            benutzer.PasswordVerificationCode = MD5Hash.CalculateMD5Hash(benutzer.BenutzerId + benutzer.Mail + benutzer.Nachname + benutzer.Vorname + benutzer.Passwort);
            benutzer.PasswortZeitstempel      = DateTime.Now;

            BenutzerRepository.EditUser(benutzer);
        }
Exemplo n.º 8
0
        public void InsertUserWithoutCodRefTest()
        {
            this.client.Delete(92);
            User userToInsert = new User
            {
                UserCode    = 92,
                UserName    = "******",
                InputDate   = DateTime.Now,
                PasswordMd5 = MD5Hash.CalculateMD5Hash("anything-else"),
                Status      = StatusUser.Guest,
            };

            this.client.Delete(userToInsert.UserCode);  // Avoid Duplicates

            Assert.True(this.client.Insert(userToInsert));
            User insertedUser = this.client.FindByCode(userToInsert.UserCode);

            Assert.NotNull(insertedUser);
            AssertExt.UsersTheSame(insertedUser, userToInsert);
            Assert.True(this.client.Delete(insertedUser.UserCode));
        }
        public void InsertUserWithCodRefTest()
        {
            this.client.Delete(91);
            User userToInsert = new User
            {
                UserCode    = 91,
                UserCodRef  = 423423423432,
                UserName    = "******",
                InputDate   = DateTime.Now,
                PasswordMd5 = MD5Hash.CalculateMD5Hash("anything"),
                Status      = StatusUser.User,
            };

            client.Delete(userToInsert.UserCode);  // Avoid Duplicates

            Assert.True(client.Insert(userToInsert));
            User insertedUser = client.FindByCode(userToInsert.UserCode);

            Assert.NotNull(insertedUser);
            AssertExt.UsersTheSame(userToInsert, insertedUser);
            Assert.True(client.Delete(insertedUser.UserCode));
        }
Exemplo n.º 10
0
        //public static User AuthenUser;

        //public Task<Tuple<bool, User>> Login(string login, string password)
        //{

        //    if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
        //    {
        //        return Task.Factory.StartNew(() =>
        //        {
        //            return new Tuple<bool, User>(false, null);
        //        });
        //    }

        //    IContext con = new Context();
        //    string otvet;

        //    XmlDocument xmlDoc = new XmlDocument();
        //    XmlElement request = xmlDoc.CreateElement("request");
        //    XmlElement q = xmlDoc.CreateElement("q");
        //    q.InnerText = "101";
        //    request.AppendChild(q);
        //    XmlElement log = xmlDoc.CreateElement("login");
        //    log.InnerText = login;
        //    request.AppendChild(log);
        //    XmlElement pass = xmlDoc.CreateElement("pass");
        //    pass.InnerText = MD5Hash.CalculateMD5Hash(password);
        //    request.AppendChild(pass);
        //    XmlElement hard = xmlDoc.CreateElement("hard");
        //    hard.InnerText = MD5Hash.CalculateMD5Hash(SerialNumber.HddSerialNumber()+SerialNumber.GpuSerialNumber());
        //    request.AppendChild(hard);
        //    XmlElement sign = xmlDoc.CreateElement("sign");
        //    sign.InnerText = MD5Hash.CalculateMD5Hash(101+MD5Hash.CalculateMD5Hash(SerialNumber.HddSerialNumber() + SerialNumber.GpuSerialNumber())+MD5Hash.CalculateMD5Hash(password));
        //    request.AppendChild(sign);
        //    XmlElement soft = xmlDoc.CreateElement("soft");
        //    soft.InnerText = "07";
        //    request.AppendChild(soft);
        //    xmlDoc.AppendChild(request);

        //    otvet = con.SendMessage(xmlDoc);

        //    xmlDoc.LoadXml(otvet);

        //    XmlNodeList nodes = xmlDoc.DocumentElement.SelectNodes("/response");

        //    foreach (XmlNode node in nodes)
        //    {
        //        string result = node.SelectSingleNode("result").InnerText;

        //        if(result=="1")
        //        {

        //            return Task.Factory.StartNew(() =>
        //            {
        //                return new Tuple<bool, User>(true, new User { FullName = node.SelectSingleNode("uname").InnerText, Login = login, Password = MD5Hash.CalculateMD5Hash(password), Token= node.SelectSingleNode("token").InnerText });
        //            });
        //        }
        //        else
        //        {
        //            return Task.Factory.StartNew(() =>
        //            {
        //                return new Tuple<bool, User>(false, null);
        //            });
        //        }
        //    }


        //    return Task.Factory.StartNew(() =>
        //    {
        //        return new Tuple<bool, User>(false, null);
        //    });
        //}
        public bool Login(string login, string password)
        {
            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
            {
                return(false);
            }

            IContext con = new Context();
            string   otvet;

            XmlDocument xmlDoc  = new XmlDocument();
            XmlElement  request = xmlDoc.CreateElement("request");
            XmlElement  q       = xmlDoc.CreateElement("q");

            q.InnerText = "101";
            request.AppendChild(q);
            XmlElement log = xmlDoc.CreateElement("login");

            log.InnerText = login;
            request.AppendChild(log);
            XmlElement pass = xmlDoc.CreateElement("pass");

            pass.InnerText = MD5Hash.CalculateMD5Hash(password);
            request.AppendChild(pass);
            XmlElement hard = xmlDoc.CreateElement("hard");

            hard.InnerText = MD5Hash.CalculateMD5Hash(SerialNumber.HddSerialNumber() + SerialNumber.GpuSerialNumber());
            request.AppendChild(hard);
            XmlElement sign = xmlDoc.CreateElement("sign");

            sign.InnerText = MD5Hash.CalculateMD5Hash(101 + MD5Hash.CalculateMD5Hash(SerialNumber.HddSerialNumber() + SerialNumber.GpuSerialNumber()) + MD5Hash.CalculateMD5Hash(password));
            request.AppendChild(sign);
            XmlElement soft = xmlDoc.CreateElement("soft");

            soft.InnerText = "07";
            request.AppendChild(soft);
            xmlDoc.AppendChild(request);

            otvet = con.SendMessage(xmlDoc);

            xmlDoc.LoadXml(otvet);

            XmlNodeList nodes = xmlDoc.DocumentElement.SelectNodes("/response");

            foreach (XmlNode node in nodes)
            {
                string result = node.SelectSingleNode("result").InnerText;

                if (result == "1")
                {
                    MainWindowViewModel._currentUser = new User {
                        FullName = node.SelectSingleNode("uname").InnerText, Login = login, Password = MD5Hash.CalculateMD5Hash(password), Token = node.SelectSingleNode("token").InnerText
                    };
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            return(false);
        }
Exemplo n.º 11
0
        public SignInAccountResponse SignInAccount(Dictionary <ParameterTypeEnum, object> parameters)
        {
            telemetryClient.TrackTrace("Starting helper");

            SignInAccountResponse result = new SignInAccountResponse
            {
                IsSucceded = true,
                ResultId   = (int)SignUpAccountResultEnum.Success
            };

            try
            {
                telemetryClient.TrackTrace("Getting parameters");

                parameters.TryGetValue(ParameterTypeEnum.Username, out global::System.Object ousername);
                string username = ousername.ToString().ToLower();

                parameters.TryGetValue(ParameterTypeEnum.Password, out global::System.Object opassword);
                string password = opassword.ToString();

                //database helpers
                DBUserAccountHelper dbUserAccountHelper = new DBUserAccountHelper(DBCONNECTION_INFO);

                telemetryClient.TrackTrace("Validating username length");

                //validate username length
                if (!RegexValidation.IsValidUsername(username))
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)SignInAccountResultEnum.InvalidUsernameLength;
                    return(result);
                }

                telemetryClient.TrackTrace("Validating username existance");

                //validate if account exists
                UserAccount userAccount = dbUserAccountHelper.GetUser(username);

                if (userAccount == null)
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)SignInAccountResultEnum.NotExists;
                    return(result);
                }
                else
                {
                    if (userAccount.password == MD5Hash.CalculateMD5Hash(password))
                    {
                        result.IsSucceded = true;
                        result.ResultId   = (int)SignInAccountResultEnum.Success;
                        result.Username   = userAccount.username;
                        result.Image      = $"{userAccount.username}.png";
                    }
                    else
                    {
                        result.IsSucceded = false;
                        result.ResultId   = (int)SignInAccountResultEnum.IncorrectPassword;
                        return(result);
                    }
                }
            }
            catch (AggregateException ex)
            {
                foreach (var innerException in ex.Flatten().InnerExceptions)
                {
                    telemetryClient.TrackException(innerException);
                }
                result.IsSucceded = false;
                result.ResultId   = (int)SignUpAccountResultEnum.Failed;
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
                result.IsSucceded = false;
                result.ResultId   = (int)SignUpAccountResultEnum.Failed;
            }

            telemetryClient.TrackTrace("Finishing helper");
            return(result);
        }
Exemplo n.º 12
0
        public async Task <SignUpAccountResponse> SignUpAccountAsync(Dictionary <ParameterTypeEnum, object> parameters)
        {
            telemetryClient.TrackTrace("Starting helper");

            SignUpAccountResponse result = new SignUpAccountResponse
            {
                IsSucceded = true,
                ResultId   = (int)SignUpAccountResultEnum.Success
            };

            try
            {
                telemetryClient.TrackTrace("Getting parameters");

                parameters.TryGetValue(ParameterTypeEnum.Username, out global::System.Object ousername);
                string username = ousername.ToString().ToLower();

                parameters.TryGetValue(ParameterTypeEnum.Password, out global::System.Object opassword);
                string password = opassword.ToString();

                parameters.TryGetValue(ParameterTypeEnum.AccountImagesContainer, out global::System.Object oaccountImagesContainer);
                string accountImagesContainer = oaccountImagesContainer.ToString();

                parameters.TryGetValue(ParameterTypeEnum.FunctionDirectory, out global::System.Object ofunctionDirectory);
                string functionDirectory = ofunctionDirectory.ToString();

                //database helpers
                DBUserAccountHelper dbUserAccountHelper = new DBUserAccountHelper(DBCONNECTION_INFO);

                telemetryClient.TrackTrace("Validating username length");

                //validate username length
                if (!RegexValidation.IsValidUsername(username))
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)SignUpAccountResultEnum.InvalidUsernameLength;
                    return(result);
                }

                telemetryClient.TrackTrace("Validating username existance");

                //validate if account exists
                UserAccount userAccount = dbUserAccountHelper.GetUser(username);

                if (userAccount != null)
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)SignUpAccountResultEnum.AlreadyExists;
                    return(result);
                }

                telemetryClient.TrackTrace("Adding account to database");

                //save username and account in mongodb
                userAccount = new UserAccount()
                {
                    username    = username,
                    password    = MD5Hash.CalculateMD5Hash(password),
                    createdDate = Timezone.GetCustomTimeZone()
                };

                //perform insert in mongodb
                await dbUserAccountHelper.CreateUserAccount(userAccount);

                telemetryClient.TrackTrace("Adding account image to storage");

                //create unique icon, upload and delete it
                var imageName = $"{username}.png";
                try
                {
                    var directory = Path.Combine(functionDirectory, "images");
                    var filePath  = Path.Combine(directory, imageName);

                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    Identicon.FromValue(username, size: 160).SaveAsPng(filePath);
                    await UploadAccountImageAsync(accountImagesContainer, imageName, filePath);

                    File.Delete(filePath);
                }
                catch
                {
                    //it doesn't matter if for some reason the icon generation fails, then ignore it and proceed as success
                }

                result.Image = imageName;
            }
            catch (AggregateException ex)
            {
                foreach (var innerException in ex.Flatten().InnerExceptions)
                {
                    telemetryClient.TrackException(innerException);
                }
                result.IsSucceded = false;
                result.ResultId   = (int)SignUpAccountResultEnum.Failed;
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
                result.IsSucceded = false;
                result.ResultId   = (int)SignUpAccountResultEnum.Failed;
            }

            telemetryClient.TrackTrace("Finishing helper");
            return(result);
        }