public User AddUserToDb(string userName, string password, string name, int age, double weight, double height, 
                                long xp, int level, string privacyName, string privacyAge, string privacyWeight, string privacyHeight)
        {
            User newUser = new User();
            //Check if username exist if it does, return null object

            int result = -1;

            using (var db = new DataAccessContext())
            {
                User user = new User
                {
                    UserName = userName,
                    Password = password,
                    Name = name,
                    Age = age,
                    Weight = weight,
                    Height = height,
                    Xp = xp,
                    Level = level,
                    PrivacyName = privacyName,
                    PrivacyAge = privacyAge,
                    PrivacyWeight = privacyWeight,
                    PrivacyHeight = privacyHeight
                };
                db.Users.Add(user);
                result = db.SaveChanges();
                if (result != -1)
                    newUser = user;
            }
            return newUser;
        }
Exemple #2
0
        /// <summary>
        /// Üyellik gerçekleştirmek için kullanılır
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="confirmPassword"></param>
        public static BusinessResponse Register(string username, string password, string confirmPassword)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(confirmPassword))
            {
                return new BusinessResponse()
                       {
                           isSuccess = false, message = "Geçersiz istek!"
                       }
            }
            ;
            else if (password != confirmPassword)
            {
                return new BusinessResponse()
                       {
                           isSuccess = false, message = "Parolalar eşleşmiyor!"
                       }
            }
            ;
            using (OfflineMessageEntities db = new OfflineMessageEntities())
            {
                DataAccess.User user = (from s in db.User where s.username == username select s).FirstOrDefault();

                if (user != null)
                {
                    return new BusinessResponse()
                           {
                               isSuccess = false, message = "Aynı isimli kullanıcı mevcut!"
                           }
                }
                ;
                else
                {
                    try
                    {
                        user          = new DataAccess.User();
                        user.username = username;
                        user.password = CalculateSha1(password);
                        user.date     = DateTime.Now;
                        user.status   = 1;
                        db.User.Add(user);
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        Log.AddLog(ex.Message, "Register");
                        return(new BusinessResponse()
                        {
                            isSuccess = false, message = "İstenmeyen bir hata oluştu! Sistem loglarını kontrol ediniz. " + DateTime.Now.ToString()
                        });
                    }

                    Log.AddLog("Üyelik Gerçekleşti", user.ID, false);

                    return(new BusinessResponse()
                    {
                        isSuccess = true, message = "Ok"
                    });
                }
            }
        }
        public static User AddUser(User u)
        {
            User returnUser = new User();

            string jsonString = JSONhelper.JSONSerializer<User>(u);
            Debug.WriteLine(jsonString);

            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create("http://localhost:3369/LevelService.svc/users/add");
            webReq.Method = "POST";                                     //Set metodetypen. Default er POST, men vi skriver det ALTID alligevel.
            webReq.ContentType = "application/json; charset=utf-8";     //Sæt contenttypen, i.e Sæt til JSON
            webReq.ContentLength = jsonString.Length;                     //Længden på strengen
            Debug.WriteLine(webReq.ContentLength.ToString() + jsonString.Length.ToString());

            using (StreamWriter sw = new StreamWriter(webReq.GetRequestStream()))   //Opret en streamwriter med vores request som parameter (aner ikke hvad requeststream er, slå det selv op)
            {
                sw.Write(jsonString); //Skyder requesten afsted.
            }

            try
            {
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();           //Opret et objekt der kan modtage svar på vores request
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))    //Opret et objekt der kan læse svaret
                {
                    string text = sr.ReadToEnd();                           //Læs svaret igennem og gem det i en streng. Det er JSON streng svaret kommer i.

                    returnUser = JSONhelper.JsonDeserialize<User>(text);    //kør json-strengen igennem deserialiseringen, med PersonModel som type objekt
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }

            return returnUser;
        }
Exemple #4
0
        public static int getRefferalLevel(string referralCode)
        {
            int refLevel = 0;

            try
            {
                if (referralCode.Length < 3)
                {
                    return(refLevel);
                }
                GlobalTransactEntitiesData db = new GlobalTransactEntitiesData();
                // PowerNowEntities pwr = new PowerNowEntities();
                DataAccess.User user = new DataAccess.User();
                var             trx  = db.Users.Where(x => x.Referal == referralCode).ToList();
                if (trx == null || trx.Count == 0)
                {
                    return(refLevel);
                }

                refLevel = 1;
                User usrObj = new DataAccess.User();
                usrObj = trx.FirstOrDefault();
                trx    = db.Users.Where(x => x.Referal == usrObj.MyReferalCode).ToList();
                if (trx == null || trx.Count == 0)
                {
                    return(refLevel);
                }
                refLevel = 2;
            }
            catch (Exception ex)
            {
                // WebLog.Log(ex.Message + "####", ex.StackTrace);
            }
            return(refLevel);
        }
Exemple #5
0
        public List<User> List()
        {
            using (SqlConnection conn = new SqlConnection(
                ConfigurationManager.ConnectionStrings["PeopleDevelopmentTracker"].ConnectionString))
            {
                conn.Open();

                using (SqlCommand cmd = new SqlCommand("SELECT UserID, Username FROM Users", conn))
                {
                    using (SqlDataReader dr = cmd.ExecuteReader())
                    {
                        List<User> users = new List<User>();
                        User thisUser;
                        while (dr.Read())
                        {
                            thisUser = new User
                            {
                                ID = dr.GetInt32(0),
                                Username = dr.GetString(1)
                            };
                        }

                        return users;
                    }
                }
            }
        }
        public ActionResult Register(RegistrationViewModel viewModel)
        {
            // това е възможно най-кратко; по принцип е както в другите проекти
            if (ModelState.IsValid)
            {
                UserRepository userRepository = new UserRepository();

                // check if the user already exists in the DB
                User existingDbUser = userRepository.GetUserByName(viewModel.Username);
                if (existingDbUser != null)
                {
                    ModelState.AddModelError("", "This user is already registered in the system!");
                    return(View());
                }

                User dbUser = new DataAccess.User();
                dbUser.Username = viewModel.Username;

                // save the user to the DB
                userRepository.RegisterUser(dbUser, viewModel.Password);

                TempData["Message"] = "User was registered successfully";
                return(RedirectToAction("Index"));
            }
            else
            {
                return(View());
            }
        }
Exemple #7
0
        public ActionResult LoginRedirect(string code)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("index", "main");
            }

            try
            {
                var template = "https://oauth.vk.com/access_token?client_id={0}&client_secret={1}&code={2}";

                var accessTokenString = HttpHelper.Get(string.Format(template, ConfigurationManager.AppSettings["VK_API"], ConfigurationManager.AppSettings["VK_SECRET"], code));

                var serializer = new JavaScriptSerializer();

                var accessToken = serializer.Deserialize<AccessTokenResult>(accessTokenString);

                var vk_user = VKHelper.GetUsers(new[] { accessToken.User_id }, accessToken.Access_token).FirstOrDefault();

                var user = DataAccess.Query<User>().FirstOrDefault(u => u.VKId == vk_user.uid);

                if (user == null)
                {
                    user = new User
                    {
                        VKId = vk_user.uid,
                        FirstName = vk_user.first_name,
                        LastName = vk_user.last_name
                    };
                }
                else
                {
                    user.FirstName = vk_user.first_name;

                    user.LastName = vk_user.last_name;
                }

                DataAccess.Save<User>(user);

                var userData = new UserData
                {
                    AccessToken = accessToken.Access_token
                };

                var ticket = new FormsAuthenticationTicket(1, user.Id.ToString(), DateTime.Now, DateTime.Now.AddSeconds(accessToken.Expires_in), true, userData.Json());

                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));

                Response.Cookies.Add(cookie);

                return RedirectToAction("index", "main");
            }
            catch
            {
                return RedirectToAction("index", "auth");
            }
        }
		public void SetValue(User aUser)
		{
			this.UserName = aUser.Use_Name;
			this.UserPassWord = aUser.Use_Password;
            this.UsePersonName = aUser.Use_PersonName;
            this.UseDateOfBirth = aUser.Use_DateOfBirth;
            this.UserEmail = aUser.Use_Email;
            this.UserPhoneNumber = aUser.Use_PhoneNumber;
            this.UserStatus = aUser.Use_Status;
		}
Exemple #9
0
        /// <summary>
        /// Bir kişi olan mesajları getirir
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="otherUserName"></param>
        /// <param name="token"></param>
        public static BusinessResponse <List <message> > getMessages(string userName, string otherUserName, string token)
        {
            DataAccess.User user      = User.getUser(userName, token);
            DataAccess.User otherUser = User.getUser(otherUserName);
            List <message>  messages;

            if (user == null || otherUser == null)
            {
                return new BusinessResponse <List <message> >()
                       {
                           isSuccess = true, message = "Kullanıcı adı yanlış girildi", Data = null
                       }
            }
            ;
            else
            {
                using (OfflineMessageEntities db = new OfflineMessageEntities())
                {
                    try
                    {
                        CultureInfo tr = new CultureInfo("tr-TR");
                        messages = (from s in db.Message.ToList()
                                    where (s.senderID == user.ID && s.recipientID == otherUser.ID) ||
                                    (s.recipientID == user.ID && s.senderID == otherUser.ID)
                                    orderby s.date descending
                                    select new message
                        {
                            date = s.date.ToString("G", tr),
                            text = s.messageContent,
                            sender = (from p in db.User where p.ID == s.senderID select p.username).FirstOrDefault(),
                            recipient = (from p in db.User where p.ID == s.recipientID select p.username).FirstOrDefault(),
                            isRead = false,
                        }).ToList();



                        Log.AddLog("Mesajlar Listelendi", user.ID, false);
                        return(new BusinessResponse <List <message> >()
                        {
                            isSuccess = true, message = "Ok", Data = messages
                        });
                    }
                    catch (Exception ex)
                    {
                        Log.AddLog(ex.Message, "getMessages");
                        return(new BusinessResponse <List <message> >()
                        {
                            isSuccess = false, message = "Kritik Hata", Data = null
                        });
                    }
                }
            }
        }
        public static bool AddUser(User user)
        {
            ServiceUserClient serviceUser = new ServiceUserClient();

            try
            {
                return serviceUser.AddUser(user);
            }
            catch (Exception)
            {
                return false;
            }
        }
Exemple #11
0
        /// <summary>
        /// Kullanıcı blocklama işlemi yapar
        /// </summary>
        /// <param name="username"></param>
        /// <param name="otherUsername"></param>
        /// <param name="token"></param>
        public static BusinessResponse addBlock(string username, string otherUsername, string token)
        {
            DataAccess.User user      = User.getUser(username, token);
            DataAccess.User otherUser = User.getUser(otherUsername);
            if (user == null || user == null)
            {
                return new BusinessResponse()
                       {
                           isSuccess = false, message = "Kullanıcı bulunamadı!"
                       }
            }
            ;
            using (OfflineMessageEntities db = new OfflineMessageEntities())
            {
                bool isAny = (from s in db.Block where s.blockerID == user.ID && s.blockedID == otherUser.ID select s).Any();

                if (isAny)
                {
                    return new BusinessResponse()
                           {
                               isSuccess = false, message = "Bloklama işlemi daha önce yapılmış"
                           }
                }
                ;
                else
                {
                    try
                    {
                        DataAccess.Block block = new DataAccess.Block();
                        block.blockerID = user.ID;
                        block.blockedID = otherUser.ID;
                        block.date      = DateTime.Now;
                        db.Block.Add(block);
                        db.SaveChanges();
                        Log.AddLog("Bloklandı", user.ID, false);
                        return(new BusinessResponse()
                        {
                            isSuccess = true, message = "Ok"
                        });
                    }
                    catch (Exception ex)
                    {
                        Log.AddLog(ex.Message, "addBlock");
                        return(new BusinessResponse()
                        {
                            isSuccess = false, message = "Kritik Hata"
                        });
                    }
                }
            }
        }
        public IEnumerable<int> GetProductIdsToFind(User userEntity)
        {
            IEnumerable<int> productsToFind;
            if (this.ProductIdType == ProductIdType.AllUsersProducts)
            {
                productsToFind = from p in userEntity.Products select p.Id;
            }
            else
            {
                productsToFind = new int[] { this.ProductId };
            }

            return productsToFind;
        }
Exemple #13
0
        /// <summary>
        /// İki kullanıcı arasında blok olup olmadığını kontrol eder
        /// </summary>
        /// <param name="username"></param>
        /// <param name="otherUsername"></param>
        /// <returns></returns>
        public static BusinessResponse <DataAccess.Block> checkBlock(string username, string otherUsername)
        {
            DataAccess.User user      = User.getUser(username);
            DataAccess.User otherUser = User.getUser(otherUsername);
            if (user == null || otherUser == null)
            {
                return new BusinessResponse <DataAccess.Block>()
                       {
                           isSuccess = false, message = "Kullanıcı Bulunamadı", Data = null
                       }
            }
            ;

            using (OfflineMessageEntities db = new OfflineMessageEntities())
            {
                List <DataAccess.Block> blocks;

                try
                {
                    blocks = (from s in db.Block where (s.blockerID == user.ID && s.blockedID == otherUser.ID) || (s.blockerID == otherUser.ID && s.blockedID == user.ID) select s).ToList();
                    if (blocks.Count > 0)
                    {
                        return new BusinessResponse <DataAccess.Block>()
                               {
                                   isSuccess = true, message = "Bloklandı!", Data = blocks[0]
                               }
                    }
                    ;                                                                                                                   //Bloklanmış
                    else
                    {
                        return new BusinessResponse <DataAccess.Block>()
                               {
                                   isSuccess = true, message = "Ok", Data = null
                               }
                    };                                                                                                     //Bloklama yok
                }
                catch (Exception ex)
                {
                    Log.AddLog(ex.Message, "checkBlock");
                    return(new BusinessResponse <DataAccess.Block>()
                    {
                        isSuccess = false, message = "Kritik Hata", Data = null
                    });
                }
            }
        }
    }
Exemple #14
0
        /// <summary>
        /// Var olan bir bloklama kaldırılır
        /// </summary>
        /// <param name="username"></param>
        /// <param name="otherUsername"></param>
        /// <param name="token"></param>
        public static BusinessResponse removeBlock(string username, string otherUsername, string token)
        {
            DataAccess.User user      = User.getUser(username, token);
            DataAccess.User otherUser = User.getUser(otherUsername);
            if (user == null || user == null)
            {
                return new BusinessResponse()
                       {
                           isSuccess = false, message = "Kullanııcı Bulunamadı"
                       }
            }
            ;
            using (OfflineMessageEntities db = new OfflineMessageEntities())
            {
                try
                {
                    List <DataAccess.Block> blocks = (from s in db.Block where s.blockerID == user.ID && s.blockedID == otherUser.ID select s).ToList();

                    if (blocks.Count > 0)
                    {
                        db.Block.RemoveRange(blocks);
                        db.SaveChanges();
                        Log.AddLog("Block Kaldırıldı", user.ID, false);
                        return(new BusinessResponse()
                        {
                            isSuccess = true, message = "Ok"
                        });
                    }
                    else
                    {
                        Log.AddLog("Block Kaldırılamadı: Bloklama yapılmamış", user.ID, false);
                        return(new BusinessResponse()
                        {
                            isSuccess = false, message = "Kaldırılacak bir blok bulunamadı!"
                        });
                    }
                }
                catch (Exception ex)
                {
                    Log.AddLog(ex.Message, "removeBlock");
                    return(new BusinessResponse()
                    {
                        isSuccess = false, message = "Kritik Hata " + DateTime.Now.ToString()
                    });
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Mesaj göndermek için kullanılan method
        /// </summary>
        /// <param name="senderUser"></param>
        /// <param name="recipientUser"></param>
        /// <param name="token"></param>
        /// <param name="message"></param>
        public static BusinessResponse sendMessage(string senderUser, string recipientUser, string token, string message)
        {
            DataAccess.User sender    = User.getUser(senderUser, token);
            DataAccess.User recipient = User.getUser(recipientUser);

            if (sender != null && recipient != null)
            {
                using (OfflineMessageEntities db = new OfflineMessageEntities())
                {
                    try
                    {
                        DataAccess.Message msg = new DataAccess.Message();
                        msg.senderID       = sender.ID;
                        msg.recipientID    = recipient.ID;
                        msg.messageContent = message;
                        msg.date           = DateTime.Now;
                        msg.isRead         = false;
                        db.Message.Add(msg);
                        db.SaveChanges();
                        Log.AddLog("Mesaj Kaydedildi", sender.ID, false);
                        return(new BusinessResponse()
                        {
                            isSuccess = true, message = "Ok"
                        });
                    }
                    catch (Exception ex)
                    {
                        Log.AddLog(ex.Message, "sendMessage");
                        return(new BusinessResponse()
                        {
                            isSuccess = false, message = "Kritik Hata"
                        });
                    }
                }
            }
            else
            {
                return new BusinessResponse()
                       {
                           isSuccess = true, message = "Geçersiz kullanıcı bilgisi!"
                       }
            };
        }
Exemple #16
0
 public ActionResult SignUp(Models.User user)
 {
     if (ModelState.IsValid)
     {
         DataAccess.User userInfo = new DataAccess.User()
         {
             FirstName = user.FirstName,
             LastName  = user.LastName,
             EmailId   = user.EmailId,
             Password  = user.Password
         };
         bool result = repo.AddUser(userInfo);
         if (!result)
         {
             return(View("Error"));
         }
     }
     return(RedirectToAction("Index"));
 }
        public ActionResult AddReference_Post(AgentReferences objData)
        {
            DataAccess.Reference objRef = new DataAccess.Reference();
            DataAccess.User objuser = new DataAccess.User();
            //Saves the Details of Referee to the User Table
            objuser.FirstName = objData.FirstName;
            objuser.LastName = objData.LastName;
            objuser.Address = objData.Address;
            objuser.State =  Convert.ToInt32(objData.State);
            objuser.City = objData.City;
            objuser.PinCode = objData.ZipCode;
            objuser.MobileNumber = objData.Phone;
            objuser.IsDeleted = false;
            objuser.Email = objData.Email;
            objuser.IsReference = true;
            this._userRepository.Add(objuser);

            //Saves the Reference Details along with the UserID obtained into the Reference Table
            objRef.Note = objData.Note;
            objRef.RefferedBy = UserId;
            objRef.Refferee = objuser.UserId;
            objRef.IsContacted = false;
            objRef.Flag = false;
            objRef.Status = "Not Yet Contacted";
            objRef.CreatedDate = DateTime.Now;
            this._reference.Add(objRef);

            #region Mailing Asynchronously

            //Asynchronously calls the SendMailToReferences method to send Mail
            AsyncMethodCaller caller = new AsyncMethodCaller(SendMailToReferences);
            //Sends the Mail to the Referee, stating been Refered
            caller.BeginInvoke(objuser.Email, base.Email ,string.Empty,"You have been Refererd","Test Body",null,null);
            //Sends the Mail to the Admin Regarding new notification
            caller.BeginInvoke(Core.BaseModel.AdminMail, string.Empty, string.Empty, "Notification About Referance", "Test Body", null, null);

            #endregion

            ViewBag.Active = "liReference";
            return RedirectToAction("Reference");
        }
        public IEnumerable<int> GetStoreNumbersToFind(IDomainContext domainContext, User userEntity)
        {
            IEnumerable<int> storeIds;
            if (this.StoreNumberType == StoreNumberType.AllStores)
            {
                storeIds = from s in domainContext.Stores select s.Id;
            }
            else
            {
                if (this.StoreNumberType == StoreNumberType.AllUsersStores)
                {
                    storeIds = from s in userEntity.Stores select s.Id;
                }
                else
                {
                    storeIds = new int[] { this.StoreNumber };
                }
            }

            return storeIds;
        }
        /// <summary>
        /// Tildeler de achievements til brugeren, som er fundet.
        /// </summary>
        /// <param name="list"></param>
        /// <param name="currentUser"></param>
        public void AssignAchievement(List<Achievement> list, User currentUser)
        {
            foreach (Achievement a in list)
            {
                using (var db = new DataAccessContext())
                {

                        int result = -1;
                        int userId = currentUser.UserId;
                        int achId = a.AchievementId;
                        result = db.Database.ExecuteSqlCommand("INSERT INTO UserAchievements VALUES(" + userId + "," + achId + ")");
                        db.SaveChanges();
                    //User dbUser = (from user in db.Users
                    //                where user.UserId == currentUser.UserId
                    //                select user).FirstOrDefault();

                    //dbUser.Achievements = list;

                    //db.SaveChanges();
                }
            }
        }
 public ActionResult Register(RegisterViewModel viewModel)
 {
     if (ModelState.IsValid)
     {
         UnitOfWork unitOfWork     = new UnitOfWork();
         User       existingDbUser = unitOfWork.UserRepository.GetUserByName(viewModel.Username);
         if (existingDbUser != null)
         {
             ModelState.AddModelError("", "This user is already registered in the system!");
             return(View());
         }
         User dbUser = new DataAccess.User();
         dbUser.Username   = viewModel.Username;
         dbUser.Name       = viewModel.Name;
         dbUser.Email      = viewModel.Email;
         dbUser.CityID     = viewModel.CityID;
         dbUser.Address    = viewModel.Address;
         dbUser.CardNumber = viewModel.CardNumber;
         dbUser.IsAdmin    = false;
         unitOfWork.UserRepository.RegisterUser(dbUser, viewModel.Password);
         bool isSaved = unitOfWork.Save() > 0;
         if (isSaved)
         {
             TempData["Message"] = "User was registered successfully";
         }
         else
         {
             TempData["ErrorMessage"] = "Ooops something went wrong";
         }
         return(RedirectToAction("Index"));
     }
     else
     {
         UnitOfWork  unitOfWork = new UnitOfWork();
         List <City> allCities  = unitOfWork.CityRepository.GetAll();
         ViewBag.AllCities = new SelectList(allCities, "ID", "Name");
         return(View());
     }
 }
Exemple #21
0
        public void Persist()
        {
            DataAccess.User item = DataAccess.UserRepository.GetByID(new Guid[] { this.ID }).FirstOrDefault();
            if (item == null)
            {
                item = BusinessLayer.UserModule.CreateUser();
            }

            Dictionary <Guid, DataAccess.UserAddress> addresses = DataAccess.UserAddressRepository
                                                                  .GetByUserID(new Guid[] { this.ID }).ToDictionary(x => x.ID);

            addresses.Add(Guid.Empty, null);             // the new addresses fall back here

            // apply changes
            item.Name = this.Name;

            BusinessLayer.UserModule.Persist(item);

            foreach (var address in this.Addresses)
            {
                address.Persist(addresses[address.ID]);
            }
        }
        /// <summary>
        /// Gets the user entity.
        /// </summary>
        /// 
        /// <returns></returns>
        private User GetUserEntity()
        {
            string userName = Thread.CurrentPrincipal.Identity.Name;
            User result = null;

            var userEntities2 = this.domainContext.Users.Where(u => String.Compare(u.Username, userName, true) == 0).Include(u => u.PersonalLocations);
            if (userEntities2.Count() == 0)
            {
                User newUser = new User() { Username = userName };
                this.domainContext.Save<User>(newUser);
                this.domainContext.SaveChanges();
                newUser = this.domainContext.Users.Where(u => u.Username == userName).Include(u => u.PersonalLocations).First();
                result = newUser;
                //                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "Couldn't find a user with user name {0} and ID {1}", userName, guid));
            }
            else
            {
                result = userEntities2.First();
            }

            return result;
        }
        private User GetUserEntity()
        {
            string userName = Thread.CurrentPrincipal.Identity.Name;
            User result = null;

            var userEntities = this.domainContext.Users.Where(u => String.Compare(u.Username, userName, true) == 0)
                .Include(u => u.Stores)
                .Include(u => u.Products)
                .Include(u => u.Products.Select(p => p.Container))
                .Include(u => u.Products.Select(p => p.Substance))
                ;
            if (userEntities.Count() == 0)
            {
                User newUser = new User() { Username = userName };
                this.domainContext.Save(newUser);
                this.domainContext.SaveChanges();
                newUser = this.domainContext.Users.Where(u => String.Compare(u.Username, userName, true) == 0)
                    .Include(u => u.Stores)
                    .Include(u => u.Products)
                    .Include(u => u.Products.Select(p => p.Container))
                    .Include(u => u.Products.Select(p => p.Substance))
                    .First();
                result = newUser;
                //                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "Couldn't find a user with user name {0} and ID {1}", userName, guid));
            }
            else
            {
                result = userEntities.First();
            }

            return result;
        }
        public void Create_Read_Update_Delete()
        {
            var p = new TestPackage();

            var user = new User
            {
                Email = Email,
                FirstName = FirstName,
                LastName = LastName,
                PhoneNumber = PhoneNumber
            };

            var user2 = new User
            {
                Email = "*****@*****.**",
                FirstName = FirstName,
                LastName = LastName,
                PhoneNumber = PhoneNumber
            };

            // Create
            var newUser = p.Tested.Create(user, Password);

            var secondUser = p.Tested.Create(user2, Password);

            p.Tested.Delete(secondUser.UserId);

            Assert.NotNull(newUser);

            // Read
            var matched = p.Tested.Get(newUser.UserId);

            Assert.NotNull(matched);
            Assert.AreEqual(matched.UserId, newUser.UserId);
            Assert.AreEqual(matched.Email, newUser.Email);
            Assert.AreEqual(matched.FirstName, newUser.FirstName);
            Assert.AreEqual(matched.LastName, newUser.LastName);
            Assert.AreEqual(matched.PhoneNumber, newUser.PhoneNumber);

            Assert.NotNull(matched.Passwords);
            Assert.IsNotEmpty(matched.Passwords);
            Assert.AreEqual(matched.Passwords.First().Hash, Password);

            // Update
            const string expected = "John";
            matched.FirstName = expected;
            p.Tested.Update(matched);
            var updated = p.Tested.Get(newUser.UserId);

            Assert.NotNull(updated);
            Assert.AreEqual(matched.UserId, updated.UserId);
            Assert.AreEqual(matched.Email, updated.Email);
            Assert.AreEqual(matched.FirstName, updated.FirstName);
            Assert.AreEqual(matched.LastName, updated.LastName);
            Assert.AreEqual(matched.PhoneNumber, updated.PhoneNumber);

            Assert.NotNull(updated.Passwords);
            Assert.IsNotEmpty(updated.Passwords);
            Assert.AreEqual(updated.Passwords.First().Hash, Password);

            // Delete
            p.Tested.Delete(newUser.UserId);
            var deleted = p.Tested.Get(newUser.UserId);
            Assert.Null(deleted);
        }
 /// <summary>
 /// Create a new User object.
 /// </summary>
 /// <param name="id">Initial value of the Id property.</param>
 /// <param name="name">Initial value of the Name property.</param>
 /// <param name="tel">Initial value of the Tel property.</param>
 /// <param name="qQ">Initial value of the QQ property.</param>
 /// <param name="birth">Initial value of the Birth property.</param>
 /// <param name="height">Initial value of the Height property.</param>
 /// <param name="weight">Initial value of the Weight property.</param>
 /// <param name="male">Initial value of the Male property.</param>
 /// <param name="married">Initial value of the Married property.</param>
 public static User CreateUser(global::System.Int32 id, global::System.String name, global::System.String tel, global::System.String qQ, global::System.DateTime birth, global::System.Int32 height, global::System.Int32 weight, global::System.Boolean male, global::System.Boolean married)
 {
     User user = new User();
     user.Id = id;
     user.Name = name;
     user.Tel = tel;
     user.QQ = qQ;
     user.Birth = birth;
     user.Height = height;
     user.Weight = weight;
     user.Male = male;
     user.Married = married;
     return user;
 }
 /// <summary>
 /// Deprecated Method for adding a new object to the User EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToUser(User user)
 {
     base.AddObject("User", user);
 }
        private static void CreateCategory(
            IDataContext dataContext,
            DefaultCategory defaultCategory,
            User user)
        {
            var category = new Category
            {
                Title = defaultCategory.Title,
                Type = defaultCategory.Type,
                User = user
            };

            dataContext.Categories.Add(category);
        }
		public void SetValue(User aUser)
		{
			this.UserName = aUser.Use_Name;
			this.UserPassWord = aUser.Use_Password;
		}
Exemple #29
0
        /// <summary>
        /// Giriş yaptıktan sonra token döner
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static BusinessResponse <DataAccess.UserToken> Login(string username, string password)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return new BusinessResponse <UserToken>()
                       {
                           isSuccess = true, message = "Kullanıcı adı veya şifre yanlış!", Data = null
                       }
            }
            ;
            using (OfflineMessageEntities db = new OfflineMessageEntities())
            {
                DataAccess.User user = User.getUser(username);

                if (user == null)
                {
                    return new BusinessResponse <UserToken>()
                           {
                               isSuccess = true, message = "Kullanıcı adı veya şifre yanlış!", Data = null
                           }
                }
                ;
                else if (user.password == CalculateSha1(password))
                {
                    try
                    {
                        List <UserToken> tokens = (from s in db.UserToken where s.userID == user.ID && s.expireDate > DateTime.Now orderby s.expireDate descending select s).ToList();
                        if (tokens.Count < 5)
                        {
                            UserToken token = new UserToken();
                            token.date       = DateTime.Now;
                            token.userID     = user.ID;
                            token.token      = createToken();
                            token.expireDate = DateTime.Now.AddDays(14);
                            db.UserToken.Add(token);
                            db.SaveChanges();
                            Log.AddLog("Giriş Yapıldı, yeni token alındı.", user.ID, false);
                            return(new BusinessResponse <UserToken>()
                            {
                                isSuccess = true, message = "OK", Data = token
                            });
                        }
                        else
                        {
                            Log.AddLog("Giriş Yapıldı", user.ID, false);
                            return(new BusinessResponse <UserToken>()
                            {
                                isSuccess = true, message = "OK", Data = tokens[0]
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.AddLog(ex.Message, "Login");
                        return(new BusinessResponse <UserToken>()
                        {
                            isSuccess = false, message = "Kritik Hata! " + DateTime.Now.ToString(), Data = null
                        });
                    }
                }
                else
                {
                    Log.AddLog("Başarısız Giriş", user.ID, false);

                    return(new BusinessResponse <UserToken>()
                    {
                        isSuccess = true, message = "Kullanıcı adı veya şifre yanlış!", Data = null
                    });
                }
            }
        }
Exemple #30
0
 public static void SetFlowUser(User user)
 {
 }
            public TestPackage()
            {
                var user1 = new User
                {
                    UserId = 1,
                    FirstName = "Jordan",
                    LastName = "Woodman",
                    Email = "*****@*****.**",
                    PhoneNumber = "4784425595",
                    Passwords = new List<Password>
                    {
                        new Password
                        {
                            Hash = "Password",
                            UserId = 1
                        }
                    }
                };

                var user2 = new User
                {
                    UserId = 2,
                    Email = "*****@*****.**"
                };

                var users = new List<User>
                {
                    user1,
                    user2,
                    new User
                    {
                        UserId = 3,
                        Email = "*****@*****.**"
                    }
                };

                var passwords = new List<Password>
                {
                    new Password
                    {
                        Hash = "*****@*****.**",
                        UserId = 1
                    }
                };

                var projects = new List<Project>
                {
                    new Project
                    {
                        ProjectId = 1,
                        UserId = 1,
                        User = user1,
                        Title = "Test",
                        Description = "this is a description",
                        StartDate = new DateTime(2015, 1, 1),
                        EndDate = new DateTime(2015, 1, 2),
                        Users = new List<User>{user2}
                    }
                };

                ProjectSetMock = new Mock<DbSet<Project>>().WithDefaultSetup(projects);
                UserSetMock = new Mock<DbSet<User>>().WithDefaultSetup(users);
                PasswordSetMock = new Mock<DbSet<Password>>().WithDefaultSetup(passwords);

                ContextProviderMock = new Mock<IProjectManagementContextProvider>()
                    .WithProjects(ProjectSetMock)
                    .WithUsers(UserSetMock)
                    .WithPasswords(PasswordSetMock);

                Tested = new UserDac(ContextProviderMock.Object);
            }
Exemple #32
0
        public ActionResult CreateUser(LoanViewModel lvm, FormCollection form)
        {
            GLobalClient cc = new GLobalClient();

            try
            {
                if (lvm != null)
                {
                    string value          = lvm.AccountsModel.Email;
                    string password       = lvm.AccountsModel.pasword;
                    string confirmpass    = lvm.AccountsModel.confirmPassword;
                    bool   validatePass   = ValidatePassword(password, confirmpass);
                    var    EncrypPassword = new CryptographyManager().ComputeHash(password, HashName.SHA256);
                    password = EncrypPassword;
                    lvm.AccountsModel.confirmPassword = password;
                    lvm.AccountsModel.pasword         = password;
                    lvm.AccountsModel.Email           = value;
                    lvm.AccountsModel.Referal         = Convert.ToString(form["Referal"]);

                    if (validatePass == false)
                    {
                        TempData["Message"] = "Password And Confirm Password Must Match";
                    }
                    else if (validatePass == true)
                    {
                        bool val = DataReaders.Validate(value);
                        if (val == true)
                        {
                            TempData["Message"] = "User Already Exist";
                            // return RedirectToAction("Signup", "Home", new { area = "" });
                            ViewBag.channel = db.MarketingChannels;
                            return(View("Signup"));
                        }
                        else if (val == false)
                        {
                            lvm.AccountsModel.Date        = DateTime.Now;
                            lvm.AccountsModel.DateTim     = DateTime.Today;
                            lvm.AccountsModel.isVissibles = 1;
                            // This is For the Api
                            // cc.CreateUser(lvm.AccountsModel);
                            User users = new DataAccess.User();
                            users.confirmPassword = lvm.AccountsModel.confirmPassword;
                            users.pasword         = lvm.AccountsModel.pasword;
                            users.Email           = lvm.AccountsModel.Email;
                            users.Date            = lvm.AccountsModel.Date;
                            users.DateTim         = lvm.AccountsModel.DateTim;
                            users.isVissibles     = lvm.AccountsModel.isVissibles;
                            users.firstname       = lvm.AccountsModel.firstname;
                            users.lastname        = lvm.AccountsModel.lastname;
                            users.Phone           = lvm.AccountsModel.Phone;
                            users.Referal         = lvm.AccountsModel.Referal;
                            //string lastid = "0";
                            //users.MyReferalCode = MyUtility.getReferralCode(lastid);
                            users.ReferralLevel = MyUtility.getRefferalLevel(users.Referal);
                            // users.MyReferalCode =
                            int id = DataCreators.CreateUser(users);

                            var channellist = Request["checkboxName"];
                            if (channellist != null)
                            {
                                string[] arr      = channellist.Split(',');
                                var      chanList = removestring(arr);
                                if (arr.Length > 0)
                                {
                                    for (var i = 0; i < arr.Length; i++)
                                    {
                                        string arrc = Convert.ToString(arr[i]);
                                        insertMarketChannel(arrc, id);
                                    }
                                }
                            }


                            if (id != 0)
                            {
                                string lastid = id.ToString();
                                users.MyReferalCode = MyUtility.getReferralCode(lastid);
                                DataCreators.updatelastID(users);

                                DataAccess.UserRole userroles = new DataAccess.UserRole();
                                userroles.UserId     = id;
                                userroles.RoleId     = Convert.ToInt16(ConfigurationManager.AppSettings["DefaultUser"]);
                                userroles.IsVissible = 1;
                                userroles.dates      = DateTime.Now;
                                DataCreators.InsertUserRoles(userroles);
                                TempData["Message"] = "User Created Succesfully";



                                //For LoggedIn User
                                Session["id"]   = lvm.AccountsModel.Email;
                                Session["User"] = Session["id"];
                                var LoggedInuser = new LogginHelper();
                                user = LoggedInuser.LoggedInUser();
                                SendEmail(lvm);

                                string Regpage = ConfigurationManager.AppSettings["DefaultRegister"];

                                return(Redirect(Regpage));

                                //return RedirectToAction("Index", "Dashboard");
                                //  return RedirectToAction("Dashboard", "Dashboard");
                            }
                            else
                            {
                                TempData["Message"] = "Registration Not Succesful Please Try Again!";
                                ViewBag.channel     = db.MarketingChannels;
                            }
                        }
                    }
                }
                else
                {
                    TempData["Message"] = "Error Creating User";
                    ViewBag.channel     = db.MarketingChannels;
                }
                return(RedirectToAction("Signup", "Home", new { area = "" }));
            }
            catch (Exception ex)
            {
                WebLog.Log(ex.Message.ToString());
                return(null);
            }
        }
 /// <summary>
 /// Create a new User object.
 /// </summary>
 /// <param name="id">Initial value of the Id property.</param>
 /// <param name="name">Initial value of the Name property.</param>
 /// <param name="password">Initial value of the Password property.</param>
 /// <param name="loginName">Initial value of the LoginName property.</param>
 public static User CreateUser(global::System.Int32 id, global::System.String name, global::System.String password, global::System.String loginName)
 {
     User user = new User();
     user.Id = id;
     user.Name = name;
     user.Password = password;
     user.LoginName = loginName;
     return user;
 }
Exemple #34
0
        public static bool InstallAll()
        {
            using (Model2Container c = new Model2Container())
            {
                Group g = new Group();
                g.Name = "公司";
                c.AddToGroup(g);

                Group g2 = new Group();
                g2.Name = "财务部";
                g2.Parent = g;
                c.AddToGroup(g2);

                Role r = new Role();
                r.Name = "经理";
                c.AddToRole(r);

                Role r2 = new Role();
                r2.Name = "主管";
                c.AddToRole(r2);

                Role r3 = new Role();
                r3.Name = "组长";
                c.AddToRole(r3);

                Role r4 = new Role();
                r4.Name = "员工";
                c.AddToRole(r4);

                User u = new User();
                u.Group = g;
                u.LoginName = "user1";
                u.Name = "总经理1";
                u.Password = "******";
                u.Roles = new EntityCollection<Role>() { r };
                c.AddToUser(u);

                User u1 = new User();
                u1.Group = g2;
                u1.LoginName = "user1";
                u1.Name = "财务主管1";
                u1.Password = "******";
                u1.Roles = new EntityCollection<Role>() { r2 };
                c.AddToUser(u1);

                User u2 = new User();
                u2.Group = g2;
                u2.LoginName = "user1";
                u2.Name = "财务专员";
                u2.Password = "******";
                u2.Roles = new EntityCollection<Role>() { r4 };
                c.AddToUser(u2);

                DataVersion v = new DataVersion();
                v.Version = 1;
                c.AddToDataVersion(v);

                AddWorlFlow();
                try
                {
                    c.SaveChanges();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }
        public User GetUser(string username, string password)
        {
            User newUser = new User();

                using (var db = new DataAccessContext())
                {
                    User theUser = (from user in db.Users
                                        .Include("Achievements")
                                        .Include("Titles")
                                        .Include("Logs")
                                    where user.UserName == username & user.Password == password
                                    select user).FirstOrDefault();

                    newUser = theUser;
                }
            return newUser;
        }
 partial void DeleteUser(User instance);
        /// <summary>
        /// Gets the user entity.
        /// </summary>
        /// <param name="entities">The entities.</param>
        /// <returns></returns>
        private User GetUserEntity()
        {
            string userName = Thread.CurrentPrincipal.Identity.Name;
            User result = null;

            var userEntities = this.unitOfWork.Users.FindWhere(u => String.Compare(u.Username, userName, true) == 0).Include("Stores").Include("PersonalLocations");
            if (userEntities.Count() == 0)
            {
                User newUser = new User() { Username = userName };
                this.unitOfWork.Users.Add(newUser);
                this.unitOfWork.Commit();
                newUser = this.unitOfWork.Users.FindWhere(u => u.Username == userName).Include("Stores").Include("PersonalLocations").First();
                result = newUser;
                //                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "Couldn't find a user with user name {0} and ID {1}", userName, guid));
            }
            else
            {
                result = userEntities.First();
            }

            return result;
        }
        public User UpdateUserProfile(string userName, string password, string name, int age, double weight, double height, long xp, int level)
        {
            User newUser = new User();

            using (var db = new DataAccessContext())
            {
                User theUser = (from user in db.Users
                                where user.UserName == userName
                                select user).FirstOrDefault();

                // Update user
                theUser.UserName = userName;
                theUser.Password = password;
                theUser.Name = name;
                theUser.Age = age;
                theUser.Weight = weight;
                theUser.Height = height;
                theUser.Xp = xp;
                theUser.Level = level;

                theUser.PrivacyName = "";
                theUser.PrivacyAge = "";
                theUser.PrivacyWeight = "";
                theUser.PrivacyHeight = "";

                newUser = theUser;

                db.SaveChanges();
            }

            return newUser;
        }
 partial void UpdateUser(User instance);
        public void UpdateUserXP(string userName, long earnedXp)
        {
            User newUser = new User();
            long oldXp;

            using (var db = new DataAccessContext())
            {
                User theUser = (from user in db.Users
                                where user.UserName == userName
                                select user).FirstOrDefault();

                // Get the old xp for user before accumulating
                oldXp = theUser.Xp;

                // Accumulate new xp
                theUser.Xp += earnedXp;

                // Check for LevelUp
                long newXp = theUser.Xp;

                // Check if User should be levelled up
                if ((newXp) > (oldXp * 1.1))
                {
                    // Increment user level
                    theUser.Level += 1;
                }

                newUser = theUser;

                db.SaveChanges();
            }

             AssignAchievement(CheckForAchievement(newUser.Xp), newUser);
        }
 partial void InsertUser(User instance);