public WebPrinciple(string userName)
        {
            moduleSettings = ModuleConfig.GetSettings();

            Data.User user = new Data.User(moduleSettings);
            identity = new SiteIdentity(userName);
        }
 public List<User> User_GetByTop(string Top, string Where, string Order)
 {
     List<Data.User> list = new List<Data.User>();
     using (SqlCommand dbCmd = new SqlCommand("sp_User_GetByTop", GetConnection()))
     {
         Data.User obj = new Data.User();
         dbCmd.CommandType = CommandType.StoredProcedure;
         dbCmd.Parameters.Add(new SqlParameter("@Top", Top));
         dbCmd.Parameters.Add(new SqlParameter("@Where", Where));
         dbCmd.Parameters.Add(new SqlParameter("@Order", Order));
         SqlDataReader dr = dbCmd.ExecuteReader();
         if (dr.HasRows)
         {
             while (dr.Read())
             {
                 list.Add(obj.UserIDataReader(dr));
             }
             dr.Close();
             //conn.Close();
         }
         else
         {
             dr.Close();
         }
     }
     return list;
 }
Esempio n. 3
0
 private Data.User ReadUserInfo()
 {
     Data.User user = new Data.User();
     user.Username = txtUserName.Text;
     user.Password = txtPassWord.Text;
     user.FacNumber = txtFacuNumber.Text;
     user.Role = radioButtons();
     return user;
 }
Esempio n. 4
0
        private Data.User ParseParameters()
        {
            var user = new Data.User
            {
                UserName = command.Parameters[0],
                Password = command.Parameters[1],
                Email = command.Parameters[2]
            };

            return user;
        }
Esempio n. 5
0
        protected override void DataPortal_DeleteSelf()
        {
            using (var ctx = Csla.Data.ObjectContextManager<ApplicationEntities>
                        .GetManager(Database.ApplicationConnection, false))
            {
                var data = new Data.User
                {
                    UserId = this.ReadProperty(UserIdProperty)
                };

                ctx.ObjectContext.Users.DeleteObject(data);

                ctx.ObjectContext.SaveChanges();
            }
        }
Esempio n. 6
0
 private Data.User ReadUserInfo()
 {
     Data.User user = new Data.User();
     user.Username = txtUserName.Text;
     user.Password = txtPassword.Text;
     user.FacNumber = txtFacNum.Text;
     if (radioStudent.Checked)
     {
         user.Role = 1;
     }
     else if (radioTeacher.Checked)
     {
         user.Role = 2;
     }
     return user;
 }
Esempio n. 7
0
        protected override void DataPortal_Insert()
        {
            using (var ctx = Csla.Data.ObjectContextManager<ApplicationEntities>
                        .GetManager(Database.ApplicationConnection, false))
            {
                var data = new Data.User();

                this.Insert(data);

                ctx.ObjectContext.AddToUsers(data);

                ctx.ObjectContext.SaveChanges();

                this.LoadProperty(UserIdProperty, data.UserId);
                this.LoadProperty(CreatedByProperty, data.CreatedBy);
                this.LoadProperty(CreatedDateProperty, data.CreatedDate);
            }
        }
Esempio n. 8
0
        protected override void DataPortal_Update()
        {
            using (var ctx = Csla.Data.ObjectContextManager<ApplicationEntities>
                        .GetManager(Database.ApplicationConnection, false))
            {
                var data = new Data.User
                {
                    UserId = this.ReadProperty(UserIdProperty)
                };

                ctx.ObjectContext.Users.Attach(data);

                this.Update(data);

                ctx.ObjectContext.SaveChanges();

                this.LoadProperty(ModifiedByProperty, data.ModifiedBy);
                this.LoadProperty(ModifiedDateProperty, data.ModifiedDate);
            }
        }
Esempio n. 9
0
 public JsonResult AddComment(int areaId, int entityId, AddComment_Post_Req model)
 {
     var commentToAdd = new Data.Comment()
     {
         AreaId = areaId,
         EntityId = entityId,
         IsActive = true,
         Text = model.Comment.Text
     };
     var userToAddCommentTo = new Data.User()
     {
         FBId = model.Comment.User.FBId,
         VKId = model.Comment.User.VKId,
         FirstName = model.Comment.User.FirstName,
         LastName = model.Comment.User.LastName,
         Thumbnail = model.Comment.User.Thumbnail
     };
     CommentsService.Add(commentToAdd, userToAddCommentTo);
     return Json(string.Empty);
 }
Esempio n. 10
0
 protected void btnSave_Click(object sender, EventArgs e)
 {
     if (Validate())
     {
         Data.User user = null;
         if (editMode == false)
         {
             user = new Data.User();
             user.Password = tbPassword.Text;
         }
         else
         {
             user = GetUser();
         }
         user.UserId = tbUserId.Text;
         user.Name = tbFullNAme.Text;
         user.Email = tbEmail.Text;
         user.UserType = ddlUserType.SelectedValue;
         user.UserTitle = tbPosition.Text;
         user.Address = tbOfficeAddress.Text;
         user.City = tbCity.Text;
         user.State = "MS";
         user.Zip = tbZipCode.Text;
         user.Phone = tbTelephone.Text;
         user.Active = bool.Parse(ddlActive.SelectedValue);
         if (editMode == false)
         {
             user.CreationTime = DateTime.Now;
             user.CreationUser = LoggedInUser.UserName;
             DatabaseContext.AddToUsers(user);
         }
         else
         {
             user.LastupdateUser = LoggedInUser.UserName;
             user.LastUpdateTime = DateTime.Now;
         }
         DatabaseContext.SaveChanges();
     }
 }
Esempio n. 11
0
        public void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            var context = HttpContext.Current;

            var userServices = Kernel.Get<UserServices>();
            User currentUser;
            if (context.User != null && context.User.Identity.IsAuthenticated)
            {
                currentUser = userServices.GetUser(int.Parse(context.User.Identity.Name));
                if (currentUser == null)
                {
                    currentUser = new Data.User { UserID = 0 };
                    FormsAuthentication.SignOut();
                }
            }
            else
                currentUser = new Data.User { UserID = 0 };

            context.Items[HttpContextItemKeys.CurrentUser] = currentUser;

            var themeServices = Kernel.Get<ThemeServices>();
            RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
            if (routeData != null)
            {
                string controllerName = routeData.GetRequiredString("controller");

                string previewTheme = context.Session != null ? (string)context.Session["ptheme"] : string.Empty;
                Theme currentTheme;
                if (routeData.GetAreaName() == "Admin")
                    currentTheme = themeServices.GetAdminTheme();
                else
                    currentTheme = themeServices.GetTheme(currentUser, controllerName, previewTheme);

                context.Items[HttpContextItemKeys.ThemeFolder] = currentTheme.FolderName;
                context.Items[HttpContextItemKeys.CurrentTheme] = currentTheme;
            }
        }
Esempio n. 12
0
        public static Dictionary<string, string> CreatAccount(CreateAccountModel model)
        {
            Dictionary<string, string> accountCreationErrors = new Dictionary<string, string>();

            if (!Data.Accessors.UsersAccessor.UserExists(model.UserName))
            {
                Data.User dbUserModel = new Data.User();
                dbUserModel.CurrentMotorcycle = model.CurrentMotorcycle;
                dbUserModel.UserName = model.UserName;
                dbUserModel.AdminLevel = 1;
                dbUserModel.Salt = DateTime.Now.Ticks.ToString();
                byte[] salt = Encoding.UTF8.GetBytes(dbUserModel.Salt);

                dbUserModel.Password = Hash(model.Password,salt);
                dbUserModel.EmailAddress = model.EmailAddress;

                Data.Accessors.UsersAccessor.CreateUser(dbUserModel);
            }
            else
            {
                accountCreationErrors.Add("AccountExists", "The user name you've selected already exists. Please select another");
            }
            return accountCreationErrors;
        }
 public List<User> User_GetByAll()
 {
     List<Data.User> list = new List<Data.User>();
     using (SqlCommand dbCmd = new SqlCommand("sp_User_GetByAll", GetConnection()))
     {
         Data.User obj = new Data.User();
         dbCmd.CommandType = CommandType.StoredProcedure;
         SqlDataReader dr = dbCmd.ExecuteReader();
         if (dr.HasRows)
         {
             while (dr.Read())
             {
                 list.Add(obj.UserIDataReader(dr));
             }
             dr.Close();
             //conn.Close();
         }
         else
         {
             dr.Close();
         }
     }
     return list;
 }
Esempio n. 14
0
 public void InsertOnSubmit(Data.User user)
 {
     _users.Add(user.FacebookUserId, user);
 }
Esempio n. 15
0
 public User(int userID)
 {
     UserID             = userID;
     dataAuthentication = new Data.User();
 }
Esempio n. 16
0
 public static void LogOut()
 {
     _currentUser = null;
 }
Esempio n. 17
0
 public TodoItem(Data.User user, string content)
 {
     AuthorEmail = user.Email;
     Content     = content;
 }
Esempio n. 18
0
 public ActionResult Register(RegisterViewModel model)
 {
     if (ModelState.IsValid)
     {
         using (SBSVEntities e = new SBSVEntities())
         {
             Data.User user = new Data.User();
             user.Email = model.Email;
             user.UserName = model.UserName;
             user.Password = model.Password;
             e.Users.AddObject(user);
             int result = e.SaveChanges();
             if (result == 1)
             {
                 return RedirectToAction("Login");
             }
         }
     }
     return View(model);
 }
 public List<User> User_Paging(string CurentPage, string PageSize)
 {
     List<Data.User> list = new List<Data.User>();
     using (SqlCommand dbCmd = new SqlCommand("sp_User_Paging", GetConnection()))
     {
         Data.User obj = new Data.User();
         dbCmd.CommandType = CommandType.StoredProcedure;
         dbCmd.Parameters.Add(new SqlParameter("@CurentPage", CurentPage));
         dbCmd.Parameters.Add(new SqlParameter("@PageSize", PageSize));
         SqlDataReader dr = dbCmd.ExecuteReader();
         if (dr.HasRows)
         {
             while (dr.Read())
             {
                 list.Add(obj.UserIDataReader(dr));
             }
             dr.Close();
             //conn.Close();
         }
         else
         {
             dr.Close();
         }
     }
     return list;
 }
Esempio n. 20
0
 public User()
 {
     userData = new Data.User();
 }
Esempio n. 21
0
 public DataSet GetAllUsers(string key)
 {
     Data.User user = new Data.User(PubConstant.ConnectionString);
     return(user.GetAllUsers(key));
 }
Esempio n. 22
0
 public bool Delete()
 {
     Data.User user = new Data.User(PubConstant.ConnectionString);
     return(user.Delete(this.userID));
 }
Esempio n. 23
0
 public bool AddToRole(int roleId)
 {
     Data.User user = new Data.User(PubConstant.ConnectionString);
     return(user.AddRole(this.userID, roleId));
 }
Esempio n. 24
0
 public bool Update()
 {
     Data.User user = new Data.User(PubConstant.ConnectionString);
     return(user.Update(this.userID, this.userName, this.password, this.trueName, this.sex, this.phone, this.email, this.employeeID, this.departmentID, this.activity, this.userType, this.style));
 }
Esempio n. 25
0
 public bool SetPassword(string UserName, string password)
 {
     byte[]    encPassword = AccountsPrincipal.EncryptPassword(password);
     Data.User user        = new Data.User(PubConstant.ConnectionString);
     return(user.SetPassword(UserName, encPassword));
 }
Esempio n. 26
0
        private bool Register()
        {
            //Try
            // Only attempt a save/update if all form fields on the page are valid
            if (Page.IsValid)
            {
                // check required fields
                int UID = -1;
                UserInfo objUserInfo = UserController.GetUserByName(PortalId, atiUserName.Text);
                // if a user is found with that username, error. this prevents you from adding a username with the same name as a superuser.
                if (objUserInfo != null)
                {
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.ErrorDialog.open('{\"html\":\"We already have an entry for the User Name.\"}');");
                    return false;
                }
                Affine.WebService.RegisterService regService = new WebService.RegisterService();
                double? timezone = null;
                if (!string.IsNullOrEmpty(atiSlimControl.LocLat))
                {
               //         timezone = regService.GetTimeZone(Convert.ToDouble(atiSlimControl.LocLat), Convert.ToDouble(atiSlimControl.LocLng));
                }
                UserInfo objNewUser = regService.InitialiseUser(PortalId);
                string fullname = atiSlimControl.FullName;
                string[] nameparts = fullname.Split(' ');
                string fname = string.Empty;
                string lname = string.Empty;
                if (nameparts.Length >= 2)
                {
                    fname = nameparts[0];
                    lname = nameparts[1];
                }

                regService.populateDnnUserInfo(PortalId, ref objNewUser, fname, lname, atiUserName.Text, atiSlimControl.Email, atiPassword.Password, atiSlimControl.Postal, atiSlimControl.Address, timezone);

                DotNetNuke.Security.Membership.UserCreateStatus userCreateStatus = UserController.CreateUser(ref objNewUser);
                if (userCreateStatus == DotNetNuke.Security.Membership.UserCreateStatus.Success)
                {
                    UID = objNewUser.UserID;
                    // DNN3 BUG
                    DotNetNuke.Services.Log.EventLog.EventLogController objEventLog = new DotNetNuke.Services.Log.EventLog.EventLogController();
                    objEventLog.AddLog(objNewUser, PortalSettings, objNewUser.UserID, atiSlimControl.Email, DotNetNuke.Services.Log.EventLog.EventLogController.EventLogType.USER_CREATED);

                    // send notification to portal administrator of new user registration
            //            DotNetNuke.Services.Mail.Mail.SendMail(objNewUser, DotNetNuke.Services.Mail.MessageType.UserRegistrationAdmin, PortalSettings);
            //            DotNetNuke.Services.Mail.Mail.SendMail(objNewUser, DotNetNuke.Services.Mail.MessageType.UserRegistrationPublic, PortalSettings);
                    DataCache.ClearUserCache(PortalId, objNewUser.Username);
                    UserController.UserLogin(PortalId, objNewUser, PortalSettings.PortalName, DotNetNuke.Services.Authentication.AuthenticationLoginBase.GetIPAddress(), true);

                    User us = new Data.User();
                    us = (User)populateUserSettings(us, objNewUser);
                    if (atiBodyComp.BirthDateVisible)
                    {
                        us.BirthDate = atiBodyComp.BirthDate;
                    }
                    SiteSetting tutorial = new SiteSetting()
                    {
                        UserSetting = us,
                        Name = "SiteIntro",
                        Value = "1"
                    };
                    entities.AddToUserSettings(us);
                    entities.SaveChanges();

                    us = entities.UserSettings.OfType<User>().FirstOrDefault( u => u.UserKey == objNewUser.UserID && u.PortalKey == objNewUser.PortalID );

                    // TODO: should have a populate function for these
                    BodyComposition bc = new BodyComposition()
                    {
                        UserSetting = us
                    };
                    if (atiBodyComp.FitnessLevelVisible)
                    {
                        bc.FitnessLevel = atiBodyComp.FitnessLevel;
                    }

                    // need height and weight conversions
                    if (atiBodyComp.WeightVisible)
                    {
                        bc.Weight = atiBodyComp.UserWeightInSystemDefault;
                    }
                    if( atiBodyComp.HeightVisible )
                    {
                        bc.Height = atiBodyComp.UserHeightInSystemDefault;
                    }
                    entities.AddToBodyComposition(bc);
                    entities.SaveChanges();

                    string body = "User registration recorded\n\n";
                           body += "ID: " + objNewUser.UserID + "\n";
                           body += "User: "******"\n";
                           body += "First Name: " + objNewUser.FirstName + "\n";
                           body += "Last Name: " + objNewUser.LastName + "\n";
                           body += "Email: " + objNewUser.Email + "\n";
                           body += "Portal: " + objNewUser.PortalID + "\n";
                           body += "User-Agent: " + Request.UserAgent + "\n\n";
             //           DotNetNuke.Services.Mail.Mail.SendMail("*****@*****.**", "*****@*****.**", "", "NEW aqufit.com USER", body, "", "HTML", "", "", "", "");
                    Affine.Utils.GmailUtil gmail = new Utils.GmailUtil();
                    gmail.Send("*****@*****.**", "User Signup: " + objNewUser.Username, body);

                    // where they brought here by a group?
                    long gid = Convert.ToInt64(hiddenGroupKey.Value);
                    if (gid > 0)
                    {   // if so then we auto add them to the group.
                        Data.Managers.LINQ.DataManager.Instance.JoinGroup(us.Id, gid, Utils.ConstsUtil.Relationships.GROUP_MEMBER);
                    }

                    // See if this person was invited by anyone.
                    ContactInvite invite = entities.ContactInvites.Include("UserSetting").FirstOrDefault(i => i.Email == us.UserEmail);
                    if (invite != null)
                    {   // this person was invited by someone so lets make them friends....
                        string stat = Affine.Data.Managers.LINQ.DataManager.Instance.AcceptFriendRequests(invite.UserSetting.Id, us.Id);
                        // TODO: assume success send for now
                    }
                    // TODO: look through a list of stored contacts to get a sugested friends list...
                }
                else
                { // registration error
                    string body = "User Registration Form FAILED (Us\n\n";
                    body += "ID: " + objNewUser.UserID + "\n";
                    body += "User: "******"\n";
                    body += "First Name: " + objNewUser.FirstName + "\n";
                    body += "Last Name: " + objNewUser.LastName + "\n";
                    body += "Email: " + objNewUser.Email + "\n";
                    body += "REGISTRATION ERROR: " + userCreateStatus.ToString() + "\n";
                    //  string errStr = userCreateStatus.ToString() + "\n\n" + atiSlimControl.ToString();
                  //  DotNetNuke.Services.Mail.Mail.SendMail("*****@*****.**", "*****@*****.**", "", "FAILED REGISTRATION", lErrorText.Text + errStr, "", "HTML", "", "", "", "");
                    Affine.Utils.GmailUtil gmail = new Utils.GmailUtil();
                    gmail.Send("*****@*****.**", "**FAIL** REGISTRATION FORM: " + objNewUser.Username, body);

                    litStatus.Text = "REGISTRATION ERROR: " + userCreateStatus.ToString();
                    return false;
                }
            }
            return true;
        }
        public async Task<JsonResult> SendPasswordEmail(ResetPasswordModel vm)
        {
            try
            {
                var user = new Data.User()
                {
                    Id = vm.Id,
                    EmailAddress = vm.EmailAddress
                };

                await _translationService.ResetUserPasswordAsync(user,
                    MailTemplates.PasswordResetSubjectFormat, 
                    MailTemplates.PasswordResetBodyFormat, 
                    ApplicationInformation.Current.GetSiteBaseUrl(this));
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
                return Json(new GenericResponse(false, ex.Message));
            }

            return Json(new GenericResponse(true, AppResources.GenericSaveSuccess));
        }
Esempio n. 28
0
 protected void Update_Click(object sender, EventArgs e)
 {
     if (Page.IsValid)
     {
         Data.User obj = new Data.User();
         obj.Id = Id;
         obj.Name = txtName.Text;
         obj.Username = txtUsername.Text;
         obj.Password = StringClass.Encrypt(txtPassword.Text);
         obj.Level = Level + "00000";
         obj.Admin = "1";
         obj.Ord = txtOrd.Text != "" ? txtOrd.Text : "1";
         obj.Active = chkActive.Checked ? "1" : "0";
         if (Insert == true)
         {
             UserService.User_Insert(obj);
         }
         else
         {
             UserService.User_Update(obj);
         }
         BindGrid();
         pnView.Visible = true;
         pnUpdate.Visible = false;
         Level = "";
         Insert = false;
     }
 }
Esempio n. 29
0
 internal void Whisper(Data.User User, string Message)
 {
     SendCommand(string.Format("tell {0} {1}", User.Username, Message));
 }
        public int TestPassword(string password)
        {
            moduleSettings = ModuleConfig.GetSettings();
            UnicodeEncoding encoding = new UnicodeEncoding();
            byte[] hashBytes = encoding.GetBytes(password);
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] cryptPassword = sha1.ComputeHash(hashBytes);

            Data.User user = new Data.User (moduleSettings);
            return user.TestPassword(ID, cryptPassword);
        }
Esempio n. 31
0
 public DataSet GetUsers(string DepartmentID)
 {
     Data.User user = new Data.User(PubConstant.ConnectionString);
     return(user.GetUsers(DepartmentID));
 }
Esempio n. 32
0
        /// <summary>
        /// To be called by the daily agent
        /// </summary>
        public static void UpdateProjectExpirations(DateTime dateToConsider, StageBitzDB dataContext)
        {
            //Get project status code ids
            int freeTrialCodeId      = Utils.GetCodeByValue("ProjectStatus", "FREETRIAL").CodeId;
            int activeCodeId         = Utils.GetCodeByValue("ProjectStatus", "ACTIVE").CodeId;
            int gracePeriodCodeId    = Utils.GetCodeByValue("ProjectStatus", "GRACEPERIOD").CodeId;
            int paymentFailedCodeId  = Utils.GetCodeByValue("ProjectStatus", "PAYMENTFAILED").CodeId;
            int suspendedCodeId      = Utils.GetCodeByValue("ProjectStatus", "SUSPENDED").CodeId;
            int freeTrialOptInCodeId = Utils.GetCodeByValue("ProjectType", "FREETRIALOPTIN").CodeId;
            int freeTrialTypeCodeId  = Utils.GetCodeByValue("ProjectType", "FREETRIAL").CodeId;


            FinanceBL financeBL = new FinanceBL(dataContext);
            CompanyBL companyBL = new CompanyBL(dataContext);
            int       companyPrimaryAdminCodeID  = Utils.GetCodeByValue("CompanyUserTypeCode", "ADMIN").CodeId;
            int       freeTrialProjectTypeCodeId = Utils.GetCodeByValue("ProjectType", "FREETRIAL").CodeId;
            string    userWebUrl   = Utils.GetSystemValue("SBUserWebURL");
            string    supportEmail = Utils.GetSystemValue("FeedbackEmail");

            #region Free Trial ending pre-notice email

            //Get the free trial projects that are about to expire in 7 days, and notify them via email
            var freeTrialProjects = from p in dataContext.Projects
                                    where (p.ProjectStatusCodeId == freeTrialCodeId && p.ProjectTypeCodeId == freeTrialProjectTypeCodeId) &&
                                    p.ExpirationDate != null
                                    select new
            {
                Project           = p,
                PaymentsSpecified = (dataContext.CreditCardTokens
                                     .Where(tk => tk.RelatedTableName == "Company" && tk.RelatedId == p.CompanyId && tk.IsActive == true)
                                     .FirstOrDefault() != null)
            };

            foreach (var projectInfo in freeTrialProjects)
            {
                StageBitz.Data.Project p = projectInfo.Project;

                int datediff = (p.ExpirationDate.Value.Date - dateToConsider).Days;
                if (datediff <= 7 && datediff >= 0)
                {
                    string freeTrialGraceEmailType = "PROJECTFREETRIALGRACE";

                    //Check if the free trial expiration pre-notice has already been sent
                    Email preNoticeEmail = dataContext.Emails.Where(em => em.EmailType == freeTrialGraceEmailType && em.RelatedId == p.ProjectId).FirstOrDefault();

                    if (preNoticeEmail == null)
                    {
                        Data.User companyPrimaryAdmin = //p.Company.CompanyUsers.Where(cu => cu.IsActive == true && cu.CompanyUserTypeCodeId == companyPrimaryAdminCodeID).FirstOrDefault().User;
                                                        (from cu in p.Company.CompanyUsers
                                                         join cur in dataContext.CompanyUserRoles on cu.CompanyUserId equals cur.CompanyUserId
                                                         where cu.IsActive && cur.CompanyUserTypeCodeId == companyPrimaryAdminCodeID && cur.IsActive
                                                         select cu).FirstOrDefault().User;

                        string companyBillingUrl = string.Format("{0}/Company/CompanyFinancialDetails.aspx?companyid={1}", userWebUrl, p.CompanyId);
                        string createProjectUrl  = string.Format("{0}/Project/AddNewProject.aspx?companyid={1}", userWebUrl, p.CompanyId);
                        EmailSender.SendProjectExpirationNoticeToCompanyAdmin(freeTrialGraceEmailType, p.ProjectId, companyPrimaryAdmin.Email1, companyPrimaryAdmin.FirstName, p.ProjectName, Utils.GetLongDateHtmlString(p.ExpirationDate.Value), companyBillingUrl, createProjectUrl, supportEmail);
                    }
                }
            }

            #endregion

            #region Project Status Updates

            // this excute after project ExpirationDate is exceded. eg:- if the agent is down for 7 days, project status should be suspended.
            var projects = from p in dataContext.Projects
                           where (p.ProjectStatusCodeId == freeTrialCodeId ||
                                  p.ProjectStatusCodeId == gracePeriodCodeId ||
                                  p.ProjectStatusCodeId == suspendedCodeId) &&
                           p.ExpirationDate != null &&
                           dateToConsider >= p.ExpirationDate
                           select new
            {
                Project           = p,
                PaymentsSpecified = (dataContext.CreditCardTokens
                                     .Where(tk => tk.RelatedTableName == "Company" && tk.RelatedId == p.CompanyId && tk.IsActive == true)
                                     .FirstOrDefault() != null)
            };

            foreach (var projectInfo in projects)
            {
                StageBitz.Data.Project p = projectInfo.Project;

                Data.User companyPrimaryAdmin = // p.Company.CompanyUsers.Where(cu => cu.IsActive == true && cu.CompanyUserTypeCodeId == companyPrimaryAdminCodeID).FirstOrDefault().User;
                                                (from cu in p.Company.CompanyUsers
                                                 join cur in dataContext.CompanyUserRoles on cu.CompanyUserId equals cur.CompanyUserId
                                                 where cu.IsActive && cur.CompanyUserTypeCodeId == companyPrimaryAdminCodeID && cur.IsActive
                                                 select cu).FirstOrDefault().User;

                string emailTemplateType = string.Empty;

                //Next expiration date is 7 days from current expiration date
                DateTime nextExpirationDate = p.ExpirationDate.Value.Date.AddDays(7);

                if (p.ProjectStatusCodeId == freeTrialCodeId)
                {
                    //Get the current Company package to check.
                    CompanyPaymentPackage companyPaymentPackage = financeBL.GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(p.CompanyId, dateToConsider);
                    DiscountCodeUsage     discountCodeUsage     = financeBL.GetDiscountCodeUsageByDate(dateToConsider, p.CompanyId);
                    //There are only two possibilities. Either user has given his permission or nothing has done.
                    //Check whether user has given the approval to continue the Free trial project.
                    if (p.ProjectTypeCodeId == freeTrialOptInCodeId)
                    {
                        // He has optin not to continue
                        if (companyPaymentPackage == null)
                        {
                            p.ProjectStatusCodeId = suspendedCodeId;
                        }
                        // He has optin to continue, with zero project package
                        else if ((companyPaymentPackage != null &&
                                  Utils.GetSystemProjectPackageDetailByPaymentPackageTypeId(companyPaymentPackage.ProjectPaymentPackageTypeId).ProjectCount == 0) ||
                                 (!companyPaymentPackage.PaymentMethodCodeId.HasValue && (discountCodeUsage == null || discountCodeUsage.DiscountCode.Discount != 100)))
                        {
                            p.ProjectStatusCodeId = suspendedCodeId;
                        }
                        else
                        {
                            p.ProjectStatusCodeId = activeCodeId;
                        }
                    }
                    else
                    {
                        p.ProjectStatusCodeId = suspendedCodeId;
                        emailTemplateType     = "PROJECTFREETRIALSUSPENDED";
                    }

                    p.ExpirationDate      = null;
                    p.LastUpdatedDate     = Utils.Now;
                    p.LastUpdatedByUserId = 0;
                }
                else if (p.ProjectStatusCodeId == gracePeriodCodeId)
                {
                    p.ProjectStatusCodeId = paymentFailedCodeId;
                    p.LastUpdatedDate     = Utils.Now;
                    p.LastUpdatedByUserId = 0;
                }
                else if (p.ProjectStatusCodeId == suspendedCodeId && (p.ProjectTypeCodeId == freeTrialOptInCodeId || p.ProjectTypeCodeId == freeTrialTypeCodeId))
                {
                    // if free trial project is manually suspended during free trial, set ExpirationDate to null at the end of free trial period.
                    p.ExpirationDate = null;
                }

                //Send the email notice if required
                if (emailTemplateType != string.Empty)
                {
                    string companyBillingUrl = string.Format("{0}/Company/CompanyFinancialDetails.aspx?companyid={1}", userWebUrl, p.CompanyId);
                    string createProjectUrl  = string.Format("{0}/Project/AddNewProject.aspx?companyid={1}", userWebUrl, p.CompanyId);
                    string expirationDate    = string.Empty;

                    if (p.ExpirationDate != null)
                    {
                        expirationDate = Utils.GetLongDateHtmlString(p.ExpirationDate.Value);
                    }
                    string pricingPlanURL = string.Format("{0}/Company/CompanyPricingPlans.aspx?companyId={1}", userWebUrl, p.CompanyId);

                    EmailSender.SendProjectExpirationNoticeToCompanyAdmin(emailTemplateType, p.ProjectId, companyPrimaryAdmin.Email1, companyPrimaryAdmin.FirstName, p.ProjectName, expirationDate, companyBillingUrl, createProjectUrl, supportEmail, pricingPlanURL);
                }
            }

            #endregion
        }
Esempio n. 33
0
        //public class ClientResponse
        //{

        //}

        public static async Task <ClientResponse> GetBooking(string pnr)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseAPIUrl + pnr);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.GetAsync("");

                string httpResponseBody = "";
                if (response.IsSuccessStatusCode)
                {
                    httpResponseBody = await response.Content.ReadAsStringAsync();

                    string test = httpResponseBody;

                    var root = JsonConvert.DeserializeObject <Data.Root>(httpResponseBody);

                    /* TODO: Kontroll av Result-tt så att patienten hittas */

                    ClientResponse res = new ClientResponse();
                    res.user = null;
                    if (root.response.dsResponse.dsResponse.User != null)
                    {
                        Data.User datauser = root.response.dsResponse.dsResponse.User.First();
                        res.user = new Models.User(datauser.ID, datauser.PersonalIdentityNumber, datauser.Name);
                    }
                    else
                    {
                        return(null);
                    }

                    res.companies = new List <Models.Company>();
                    if (root.response.dsResponse.dsResponse.Company != null)
                    {
                        foreach (var datacompany in root.response.dsResponse.dsResponse.Company)
                        {
                            Models.Company newComp = new Models.Company();
                            newComp.Address      = datacompany.Address;
                            newComp.ID           = datacompany.ID;
                            newComp.Mail         = datacompany.Mail;
                            newComp.OpeningHours = datacompany.OpeningHours;
                            newComp.PhoneNumber  = datacompany.PhoneNumber;
                            newComp.Picture      = datacompany.Picture;
                            newComp.Name         = datacompany.Name;


                            res.companies.Add(newComp);
                        }
                    }


                    res.bookings = new List <Models.Booking>();
                    if (root.response.dsResponse.dsResponse.Booking != null)
                    {
                        foreach (var databooking in root.response.dsResponse.dsResponse.Booking)
                        {
                            Models.Booking newBooking = new Models.Booking();
                            newBooking.Company     = res.companies.FirstOrDefault(x => x.ID == databooking.Company_ID);
                            newBooking.Date        = databooking.Datum;
                            newBooking.Description = databooking.Dsc;
                            newBooking.Status      = databooking.Status;
                            newBooking.ID          = databooking.ID;


                            res.bookings.Add(newBooking);
                        }
                    }


                    return(res);
                }
            }
            return(null);
        }
Esempio n. 34
0
 public DataSet GetUsersByType(string usertype, string key)
 {
     Data.User user = new Data.User(PubConstant.ConnectionString);
     return(user.GetUsersByType(usertype, key));
 }
Esempio n. 35
0
 /// <summary>
 /// Called when this form is entered (using switchTo(formName)).
 /// </summary>
 /// <param name="from">The calling form.</param>
 /// <param name="user">An optionnal user.</param>
 public virtual void Entered(StateControl from, Data.User user, Data.User returnUser)
 {
     this.Show();
     this.CurrentUser = user;
     this.returnUser = returnUser;
 }
Esempio n. 36
0
 public bool HasUser(string userName)
 {
     Data.User user = new Data.User(PubConstant.ConnectionString);
     return(user.HasUser(userName));
 }
Esempio n. 37
0
 /// <summary>
 /// Invokes  <see cref="EditRequested"/>
 /// </summary>
 /// <param name="user">The user selected in the view.</param>
 private void Edit(Data.User user)
 {
     EditRequested?.Invoke(user);
 }
Esempio n. 38
0
        private async Task FillDB(DetiContext db)
        {
            var user = await _db.Users.FirstOrDefaultAsync(u => u.Login == "hackadmin" && u.Password == Util.GetEncryptedBytes("hackadmin"));

            if (user == null)
            {
                var admin = new Data.User()
                {
                    Login      = "******",
                    Password   = Util.GetEncryptedBytes("hackadmin"),
                    FirstName  = "--", LastName = "---",
                    MiddleName = "---", Role =
                        Role.Admin
                };

                var profession = new Data.Profession()
                {
                    Name         = "Программист",
                    ImgURL       = @"https://sun9-29.userapi.com/1-WgAmlkOwd-1_sW7Wp_uUlWFEjHdkAsZLxiLg/JCI0QEBnKX8.jpg",
                    ProfessionID = 0
                };

                var profession1 = new Data.Profession()
                {
                    Name         = "Специалист по VR",
                    ImgURL       = @"https://sun9-29.userapi.com/1-WgAmlkOwd-1_sW7Wp_uUlWFEjHdkAsZLxiLg/JCI0QEBnKX8.jpg",
                    ProfessionID = 0
                };

                var category = new Data.Category()
                {
                    ImgURL     = @"https://sun9-29.userapi.com/1-WgAmlkOwd-1_sW7Wp_uUlWFEjHdkAsZLxiLg/JCI0QEBnKX8.jpg",
                    Name       = "Информационные технологии",
                    CategoryID = 0
                };

                _db.ProfessionCategories.Add(new ProfessionCategory()
                {
                    Category = category, Profession = profession
                });
                _db.ProfessionCategories.Add(new ProfessionCategory()
                {
                    Category = category, Profession = profession1
                });

                var course = new Data.Course()
                {
                    Name            = "Изучение основ Java",
                    Address         = "ул. Пушкина д. 10а",
                    ApproxTime      = "15",
                    DifficultyLevel = "2",
                    ImgURL          = "http://www.juntech.ru/sites/default/files/inline-images/java.png",
                    Info            = "На занятиях этого направления Вы: " +
                                      "- познакомитесь с синтаксисом языка; " +
                                      "- рассмотрите элементы объектно-ориентированного программирования; " +
                                      "- поработаете с данными и алгоритмами; " +
                                      "- изучите графику и интерфейсы;" +
                                      "-освоите один из самых популярных языков. " +
                                      "Рекомендовано для 12 - 18 лет.",
                    ScheduleList = new List <Schedule>()
                    {
                        new Schedule()
                        {
                            Marker = "ПН-ПТ",
                            Time   = "15:30"
                        },
                        new Schedule()
                        {
                            Marker = "СБ",
                            Time   = "12:10"
                        }
                    },
                };

                var course1 = new Data.Course()
                {
                    Name            = "Разработка VR и AR приложений",
                    Address         = "ул. Пушкина д. 10а",
                    ApproxTime      = "21",
                    DifficultyLevel = "5",
                    ImgURL          = "http://www.juntech.ru/sites/default/files/inline-images/%D0%B2%D0%B8%D0%B0%D1%80.png",
                    Info            = "На занятиях этого направления Вы: " +
                                      "- научитесь разбираться в технологиях и адаптировать их под свои проекты; " +
                                      "- будете применять самостоятельные разработки приложений виртуальной (VR), дополненной (AR) и смешанной (MR) реальности для различных устройств; " +
                                      "- разберете приемы программирования в контексте игрового движка Unity. " +
                                      "- освоите ААА-пайплайн в 3D- моделировании (разработка lowpoly-модели с разверткой и простой текстурой). " +
                                      "Рекомендовано для 12 - 18 лет.",
                    ScheduleList = new List <Schedule>()
                    {
                        new Schedule()
                        {
                            Marker = "ПН-ПТ",
                            Time   = "13:20"
                        },
                        new Schedule()
                        {
                            Marker = "СБ",
                            Time   = "10:00"
                        }
                    },
                };

                var skill = new Skill()
                {
                    Name = "Программирование"
                };
                _db.ProfessionCourses.Add(new ProfessionCourse()
                {
                    Profession = profession, Course = course
                });
                _db.ProfessionCourses.Add(new ProfessionCourse()
                {
                    Profession = profession, Course = course1
                });
                _db.CourseSkills.Add(new CourseSkills()
                {
                    Course = course, Skill = skill
                });
                _db.CourseSkills.Add(new CourseSkills()
                {
                    Course = course1, Skill = skill
                });
                _db.Users.Add(admin);
                await _db.SaveChangesAsync();
            }
            ;
        }
 public WebPrinciple(int ID)
 {
     moduleSettings = ModuleConfig.GetSettings();
     Data.User user = new Data.User(moduleSettings);
     identity = new SiteIdentity(ID);
 }
Esempio n. 40
0
        protected void bUserSetup_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                int UID = -1;
                UserInfo objUserInfo = UserController.GetUserByName(PortalId, atiUserNameSetup.Text);
                // if a user is found with that username, error. this prevents you from adding a username with the same name as a superuser.
                if (objUserInfo != null)
                {
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.ErrorDialog.open('{\"html\":\"We already have an entry for the User Name.\"}');");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(atiSlimFBSetup.Postal))
                {
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.ErrorDialog.open('{\"html\":\"Postal/Zip is required to give you accurate gym, route, and user information, in your location.\"}');");
                    return;
                }
                else if (atiPasswordSetup.Password != atiPasswordSetup.Confirm)
                {
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.ErrorDialog.open('{\"html\":\"Password and Confirmation do not match.\"}');");
                    return;
                }
                Affine.WebService.RegisterService regService = new WebService.RegisterService();
                UserInfo objNewUser = regService.InitialiseUser(PortalId); // TODO: this method

                // TODO: need a TimeZone control

                string fname = hiddenGivenName.Value;
                string lname = hiddenFamilyName.Value;
                string fullname = fname + " " + lname;
                //string uuid = Guid.NewGuid().ToString().Substring(0, 15);
                string pass = atiPasswordSetup.Password;
                string email = hiddenEmail.Value;
                regService.populateDnnUserInfo(PortalId, ref objNewUser, fname, lname, atiUserNameSetup.Text, email, pass, atiSlimFBSetup.Postal, atiSlimFBSetup.Address, null);

                DotNetNuke.Security.Membership.UserCreateStatus userCreateStatus = UserController.CreateUser(ref objNewUser);
                if (userCreateStatus == DotNetNuke.Security.Membership.UserCreateStatus.Success)
                {
                    UID = objNewUser.UserID;
                    // DNN3 BUG
                    DotNetNuke.Services.Log.EventLog.EventLogController objEventLog = new DotNetNuke.Services.Log.EventLog.EventLogController();
                    objEventLog.AddLog(objNewUser, PortalSettings, objNewUser.UserID, atiSlimControl.Email, DotNetNuke.Services.Log.EventLog.EventLogController.EventLogType.USER_CREATED);

                    // send notification to portal administrator of new user registration
                    //            DotNetNuke.Services.Mail.Mail.SendMail(objNewUser, DotNetNuke.Services.Mail.MessageType.UserRegistrationAdmin, PortalSettings);
                    //            DotNetNuke.Services.Mail.Mail.SendMail(objNewUser, DotNetNuke.Services.Mail.MessageType.UserRegistrationPublic, PortalSettings);
                    DataCache.ClearUserCache(PortalId, objNewUser.Username);
                    UserController.UserLogin(PortalId, objNewUser, PortalSettings.PortalName, DotNetNuke.Services.Authentication.AuthenticationLoginBase.GetIPAddress(), true);

                    User us = new Data.User();
                    us = (User)populateUserSettings(us, objNewUser);
                    try
                    {
                        us.FBUid = Convert.ToInt64(hiddenIdentifier.Value);
                    }
                    catch (Exception) { }
                    entities.AddToUserSettings(us);
                    entities.SaveChanges();

                    // TODO: should have a populate function for these
                    BodyComposition bc = new BodyComposition()
                    {
                        UserSetting = us
                    };
                    if (atiBodyComp.Visible && atiBodyComp.FitnessLevelVisible)
                    {
                        bc.FitnessLevel = atiBodyComp.FitnessLevel;
                    }

                    // need height and weight conversions
                    if (atiBodyComp.Visible && atiBodyComp.WeightVisible)
                    {
                        bc.Weight = atiBodyComp.UserWeightInSystemDefault;
                    }
                    if (atiBodyComp.Visible && atiBodyComp.HeightVisible)
                    {
                        bc.Height = atiBodyComp.UserHeightInSystemDefault;
                    }
                    entities.AddToBodyComposition(bc);
                    entities.SaveChanges();

                    string body = "User registration recorded\n\n";
                    body += "ID: " + objNewUser.UserID + "\n";
                    body += "User: "******"\n";
                    body += "First Name: " + objNewUser.FirstName + "\n";
                    body += "Last Name: " + objNewUser.LastName + "\n";
                    body += "Email: " + objNewUser.Email + "\n";
                    body += "Portal: " + objNewUser.PortalID + "\n";
                    //           DotNetNuke.Services.Mail.Mail.SendMail("*****@*****.**", "*****@*****.**", "", "NEW aqufit.com USER", body, "", "HTML", "", "", "", "");
                    Affine.Utils.GmailUtil gmail = new Utils.GmailUtil();
                    gmail.Send("*****@*****.**", "User Signup: " + objNewUser.Username, body);

                    // See if this person was invited by anyone.
                    ContactInvite invite = entities.ContactInvites.Include("UserSetting").FirstOrDefault(i => i.Email == us.UserEmail);
                    if (invite != null)
                    {   // this person was invited by someone so lets make them friends....
                        string stat = Affine.Data.Managers.LINQ.DataManager.Instance.AcceptFriendRequests(invite.UserSetting.Id, us.Id);
                        // TODO: assume success send for now
                    }
                    Response.Redirect(Convert.ToString(Settings["LandingPage"]), true);
                }
                else
                { // registration error
                    string body = "User registration FAILED \n\n";
                    body += "ID: " + objNewUser.UserID + "\n";
                    body += "User: "******"\n";
                    body += "First Name: " + fname + "\n";
                    body += "Last Name: " + lname + "\n";
                    body += "Email: " + email + "\n";
                    body += "Status: " + userCreateStatus.ToString();
                    //  string errStr = userCreateStatus.ToString() + "\n\n" + atiSlimControl.ToString();
                    //  DotNetNuke.Services.Mail.Mail.SendMail("*****@*****.**", "*****@*****.**", "", "FAILED REGISTRATION", lErrorText.Text + errStr, "", "HTML", "", "", "", "");
                    Affine.Utils.GmailUtil gmail = new Utils.GmailUtil();
                    gmail.Send("*****@*****.**", "**FAIL** RPX User Signup: " + objNewUser.Username, body);
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.ErrorDialog.open('{\"html\":\"" + userCreateStatus.ToString() + "\"}');");
                }
            }
            else
            {
                RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.ErrorDialog.open('{\"html\":\"\"}');");
            }
        }
        public static WebPrinciple ValidateLogin(string userName, string password)
        {
            String moduleSettings = ModuleConfig.GetSettings();
            string cryptPassword = EncryptPasswordS(password);
            Data.User user = new Data.User(moduleSettings);
            int newID = -1; // user.ValidateLogin(userName, cryptPassword);

            if (newID > -1 )
                return new WebPrinciple(newID);
            else
                return null;
        }
Esempio n. 42
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                StageBitzException ex = StageBitzException.GetLastException();

                if (ex != null)
                {
                    plcGeneric.Visible = false;

                    if (ex is ConcurrencyException)
                    {
                        //Find the project id
                        int relatedId = 0;
                        switch (ex.Origin)
                        {
                        case ExceptionOrigin.ItemBriefDetails:
                            relatedId = DataContext.ItemBriefs.Where(ib => ib.ItemBriefId == ex.RelatedId).FirstOrDefault().ProjectId;
                            break;

                        case ExceptionOrigin.ItemBriefList:
                        case ExceptionOrigin.ProjectDetails:
                        case ExceptionOrigin.ItemBriefTasks:
                        case ExceptionOrigin.UserDetails:
                            relatedId = ex.RelatedId;
                            break;

                        default:
                            break;
                        }

                        //Generate the link
                        switch (ex.Origin)
                        {
                        case ExceptionOrigin.UserDetails:
                            lnkPage.InnerText = "Go Back";
                            lnkPage.HRef      = "~/Personal/UserDetails.aspx";
                            break;

                        default:
                            lnkPage.InnerText = "View Updates";
                            lnkPage.HRef      = string.Format("~/Project/ProjectNotifications.aspx?projectid={0}", relatedId);
                            break;
                        }

                        plcConcurrency.Visible = true;
                    }
                    else
                    {
                        switch (ex.Origin)
                        {
                        case ExceptionOrigin.ProjectClose:
                            plcClosedProject.Visible = true;
                            break;

                        case ExceptionOrigin.ItemDelete:
                            DeletedItemDatails itemDeleteData = this.GetBL <InventoryBL>().GetDeleteItemData(ex.RelatedId);
                            //string ItemDeleteMessage = string.Concat("This Item was deleted by ",itemDeleteData.ItemDeletedUser," on ", itemDeleteData.ItemDeletedDate,". Please contact ","<a href='mailto:", itemDeleteData.ItemDeletedUserEmail, "'>", itemDeleteData.ItemDeletedUser, "</a>");
                            ltrItemDeletedUser.Text           = itemDeleteData.ItemDeletedUser;
                            ltrDeletedDate.Text               = Support.FormatDate(itemDeleteData.ItemDeletedDate.Date);
                            lnkItemDeletedUserEmail.HRef      = "mailto:" + itemDeleteData.ItemDeletedUserEmail;
                            lnkItemDeletedUserEmail.InnerText = itemDeleteData.ItemDeletedUser;
                            string[] msgArray = ex.Message.Split('=');
                            if (msgArray.Length > 1)
                            {
                                lnkInventoryPage.HRef = string.Format("~/Inventory/CompanyInventory.aspx?CompanyId={0}", msgArray[1]);
                            }
                            plcItemDeleted.Visible = true;
                            break;

                        case ExceptionOrigin.ItemNotVisibile:
                            plcItemNotVisibile.Visible = true;
                            Data.Item item = this.GetBL <InventoryBL>().GetItem(ex.RelatedId);
                            if (item != null)
                            {
                                Data.User locationManager = this.GetBL <InventoryBL>().GetContactBookingManager(item.CompanyId.Value, item.LocationId);
                                lnkInventoryAdminUserProfile.Text = string.Format("{0} {1}", locationManager.FirstName, locationManager.LastName);

                                if (StageBitz.Common.Utils.CanAccessInventory(item.CompanyId.Value, this.UserID))
                                {
                                    lnkInventoryPageItemNotVisible.HRef      = string.Format("~/Inventory/CompanyInventory.aspx?CompanyId={0}", item.CompanyId.Value);
                                    lnkInventoryAdminUserProfile.NavigateUrl = string.Format("~/Personal/UserDetails.aspx?userId={0}", locationManager.UserId);
                                }
                                else
                                {
                                    lnkGotoDashboard.Visible = true;
                                    lnkInventoryPageItemNotVisible.Visible   = false;
                                    lnkInventoryAdminUserProfile.NavigateUrl = string.Format("mailto:{0}", locationManager.Email1);
                                }
                            }
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
        }
        public void UpdateNewUserAchievements()
        {
            Mock <IAchievementManager>    achievementManagerMock = new Mock <IAchievementManager>();
            Mock <ISteamCommunityManager> communityManagerMock   = new Mock <ISteamCommunityManager>();

            // expect
            User user = new User {
                FacebookUserId = 1234, SteamUserId = "user1"
            };

            Data.User dataUser = new Data.User {
                FacebookUserId = 1234, SteamUserId = "user1"
            };
            achievementManagerMock.Setup(rep => rep.GetUser(user.FacebookUserId))
            .Returns(dataUser).Verifiable();

            AchievementXmlParser   achievementXmlParser = new AchievementXmlParser();
            List <UserAchievement> userAchievements     =
                achievementXmlParser.ParseClosed(File.ReadAllText("cssAchievements.xml")).ToList();

            userAchievements.ForEach(
                userAchievement =>
                userAchievement.Game =
                    new Game
            {
                Id       = 240,
                ImageUrl =
                    "http://media.steampowered.com/steamcommunity/public/images/apps/10/af890f848dd606ac2fd4415de3c3f5e7a66fcb9f.jpg",
                Name           = "Counter-Strike: Source",
                PlayedRecently = true,
                StatsUrl       =
                    String.Format("http://steamcommunity.com/id/{0}/games/?xml=1", user.SteamUserId),
                StoreUrl = "http://store.steampowered.com/app/10"
            });

            communityManagerMock.Setup(rep => rep.GetAchievements(user.SteamUserId))
            .Returns(new List <UserAchievement>()).Verifiable();

            achievementManagerMock.Setup(rep => rep.GetUser(user.SteamUserId))
            .Returns(dataUser).Verifiable();
            achievementManagerMock.Setup(rep => rep.UpdateAchievements(It.IsAny <IEnumerable <Data.UserAchievement> >()))
            .Returns(5).Verifiable();

            ICollection <Game> games = new GameXmlParser().Parse(File.ReadAllText("games.xml"));

            communityManagerMock.Setup(rep => rep.GetGames(user.SteamUserId))
            .Returns(games).Verifiable();

            Achievement[] dataAchievements = new[] { new Achievement {
                                                         Description = "x", GameId = 1, Id = 1,
                                                     } };
            achievementManagerMock.Setup(
                rep => rep.GetUnpublishedAchievements(user.SteamUserId, DateTime.UtcNow.Date.AddDays(-2)))
            .Returns(dataAchievements).Verifiable();
            achievementManagerMock.Setup(
                rep =>
                rep.UpdateHidden(user.SteamUserId, It.IsAny <IEnumerable <int> >()))
            .Verifiable();

            // execute
            IAchievementService service =
                new AchievementService(achievementManagerMock.Object, communityManagerMock.Object);

            service.UpdateNewUserAchievements(user);

            // verify
            achievementManagerMock.Verify();
            communityManagerMock.Verify();
        }
Esempio n. 44
0
 public static void Delete(int userId)
 {
     String moduleSettings = ModuleConfig.GetSettings();
     Data.User dU = new Data.User(moduleSettings);
     dU.Delete(userId);
 }
Esempio n. 45
0
 public void DeleteOnSubmit(Data.User user)
 {
     _users.Remove(user.FacebookUserId);
 }
Esempio n. 46
0
 public User(DataRow row)
 {
     _user = new Data.User(ModuleSettings);
     LoadFromRow(row);
 }
Esempio n. 47
0
        public Guid Add(UserInfo userInfo)
        {
            var user = new Data.User(userInfo.FirstName, userInfo.LastName, userInfo.Age, userInfo.Login, userInfo.Password);

            return(user.Id);
        }
Esempio n. 48
0
 //public User(WebPrinciple existingPrincipal)
 //{
 //    _user = new Fpp.WebModules.Data.User(ModuleSettings);
 //    ID = ((SiteIdentity)existingPrincipal.Identity).UserID;
 //    LoadFromID();
 //}
 public User(String userName, String Password)
 {
     _user = new Data.User(ModuleSettings);
     LoadFromRow(_user.Retrieve(userName, Password));
 }
Esempio n. 49
0
 /// <summary>
 /// Called when a user connects
 /// </summary>
 /// <param name="Message"></param>
 internal void OnUserJoined(EMMServerMessage Message)
 {
     Data.User user = mUserManager.OnUserJoinedMessage(Message);
     mOnlineUsers.Add(user.Username);
 }
Esempio n. 50
0
 public static bool User_Insert(Data.User data)
 {
     return(db.User_Insert(data));
 }
        /// <summary>
        /// Gets the user.
        /// </summary>
        /// <param name="facebookUserId">The facebook user id.</param>
        /// <returns></returns>
        public Models.User GetUser(long facebookUserId)
        {
            Data.User user = _manager.GetUser(facebookUserId);

            return Map(user);
        }
Esempio n. 52
0
 public static bool User_Update(Data.User data)
 {
     return(db.User_Update(data));
 }
Esempio n. 53
0
        private void Save()
        {
            try
            {
                for (int i = 0; i < Users.Count; i++)
                {
                    if (ManipulatedUser.Email == Users[i].Email && ManipulatedUser.ID != Users[i].ID) // als de email van een gebruiker gelijk is aan de email van een al bestaande, maar andere gebruiker dan zichzelf
                    {
                        throw new InvalidOperationException(Properties.Resources.ErrorEmailAlreadyInUse);
                    }
                }

                Data.User user;

                if (!IsNewUser)
                {
                    user = _usersRepository.GetUserById(ManipulatedUser.ID);
                }
                else
                {
                    user = new Data.User();
                }

                user.LastName    = ManipulatedUser.LastName;
                user.FirstName   = ManipulatedUser.FirstName;
                user.Address     = null; // we stop using address
                user.Password    = ManipulatedUser.Password;
                user.Email       = ManipulatedUser.Email;
                user.PhoneNumber = ManipulatedUser.PhoneNumber;
                user.NFCUID      = ManipulatedUser.NFCUID;
                user.Role        = SelectedRole;

                if (IsNewUser == false)
                {
                    if (MainWindowViewModel.User.ID == ManipulatedUser.ID) // check if the user beeing updated is the same as the current logged in user.
                    {
                        if (MainWindowViewModel.User.Role != SelectedRole)
                        {
                            throw new InvalidOperationException(Properties.Resources.ErrorCannotChangeYourOwnRole);
                        }
                    }
                    _usersRepository.UpdateUser(user);
                    CancelRequested?.Invoke();
                }
                else
                {
                    try
                    {
                        System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();

                        saveFileDialog.Filter           = "txt files (*.txt)|*.txt";
                        saveFileDialog.FilterIndex      = 2;
                        saveFileDialog.RestoreDirectory = true;
                        saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                        if (saveFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            using (StreamWriter writer = new StreamWriter(saveFileDialog.FileName))
                            {
                                writer.WriteLine(Properties.Resources.WarningChangePassword);
                                writer.WriteLine($"password: {user.Password}");
                                writer.Close();
                            }
                        }
                        else
                        {
                            // show pwd in msbx, because when the pwd cannot be saved in a textfile, the user cannot login.
                            System.Windows.MessageBox.Show(Properties.Resources.ErrorCreateUser.Replace("{password}", ManipulatedUser.Password));
                        }

                        _usersRepository.AddUser(user);
                        CancelRequested?.Invoke();
                    }
                    catch (ArgumentException ex)
                    {
                        ErrorHandler.ThrowError(0, ex.Message);
                    }
                    catch (InvalidOperationException ex)
                    {
                        ErrorHandler.ThrowError(0, ex.Message);
                    }
                    catch (Exception)
                    {
                        // when something goes wrong, show pwd in msbx, because when the pwd cannot be saved in a textfile, the user cannot login.
                        System.Windows.MessageBox.Show(Properties.Resources.ErrorCreateUser.Replace("{password}", ManipulatedUser.Password));
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.ThrowError(0, ex.Message);
            }
        }
Esempio n. 54
0
 /// <summary>
 /// Saves the personal phone.
 /// </summary>
 private void SavePersonalPhone()
 {
     Data.User user = this.GetBL <PersonalBL>().GetUser(UserID);
     user.Phone1 = txtPersonalPhone.Text.Trim();
 }
Esempio n. 55
0
 public User()
 {
     _user = new Data.User(ModuleSettings);
     _addr = new Address();
 }
 internal static User MapTo(this Data.User user)
 {
     return(new User {
         Id = user.Id, Name = user.Name, Age = user.Age
     });
 }
Esempio n. 57
0
 public User(int existingUserID)
 {
     _user = new Data.User(ModuleSettings);
     ID = existingUserID;
     LoadFromID();
 }
Esempio n. 58
0
 public User()
     : base()
 {
     AccessUser = new Data.User();
 }
Esempio n. 59
0
 public User(String email)
 {
     _user = new Data.User(ModuleSettings);
     LoadFromRow(_user.Retrieve(email));
 }
Esempio n. 60
0
 public User(Int32 UserID)
     : base()
 {
     AccessUser = new Data.User(UserID);
 }