public static void Initialize()
        {
            Log.Verbose("Initializing CloPayloadCreator");

            _analyticsUserName = CloudConfigurationManager.GetSetting("LoMo.AnalyticsApi.UserName");
            _analyticsPassword = CloudConfigurationManager.GetSetting("LoMo.AnalyticsApi.Password");
            Uri analyticsBaseUri = new Uri(CloudConfigurationManager.GetSetting("LoMo.AnalyticsApi.Address"));

            _analyticsTokenUri = new Uri(analyticsBaseUri, "token");

            _lstTestEmailAddress = CloudConfigurationManager.GetSetting("LoMo.EmailJobs.TestEmailAddress").Split(',').ToList();
            _testUserId          = CloudConfigurationManager.GetSetting("LoMo.EmailJobs.TestUserId");

            string storageSetting          = CloudConfigurationManager.GetSetting(StorageSetting);
            string emailJobsQueueName      = CloudConfigurationManager.GetSetting(EmailJobsQueueNameSetting);
            string userDalConnectionString = CloudConfigurationManager.GetSetting(UsersDalConnectionStringSetting);

            Log.Verbose("Finished reading settings for clopayloadcreator");

            _usersDal = new UsersDal(userDalConnectionString);

            //Initialize the jobs queue
            _emailJobsQueue = new JobsQueue <EmailCargo>(storageSetting, emailJobsQueueName);
            Log.Verbose("Instantiated Users dal and Email Jobs queue");
        }
        public ActionResult Submit()
        {
            UsersDal     dal      = new UsersDal();
            string       userName = Request.Form["UserName"].ToString();
            string       password = Request.Form["Password"].ToString();
            List <Users> objUsers = (from usr in dal.users where usr.UserName == userName select usr).ToList <Users>();

            if (objUsers.Count <Users>() != 0)
            {
                if (objUsers[0].Password == password)
                {
                    Session["Id"] = objUsers[0].Id;
                    switch (objUsers[0].Permission)
                    {
                    case "1":
                        return(RedirectToAction("Home", "Admin"));

                    //return View();
                    case "2":
                        return(RedirectToAction("Home", "Lecturer"));

                    case "3":
                        return(RedirectToAction("Home", "Student"));
                        //return RedirectToAction("ShowStudentSearch", "Student");
                    }
                }
            }
            ViewBag.LoginError = "User Name or Password invalid";
            //return RedirectToAction("StudentPage", "Student");
            return(View("Submit"));
        }
示例#3
0
        // GET: User
        public ActionResult Gestion(Users req)
        {
            if (ModelState.IsValid)
            {
                UsersDal usersDal  = new UsersDal();
                string   email     = Session["Log"].ToString();
                Users    connected = usersDal.User.Where(d => d.Email == email).First();
                connected.Email        = req.Email;
                connected.First_Name   = req.First_Name;
                connected.Last_Name    = req.Last_Name;
                connected.Password     = req.Password;
                connected.Phone_Number = req.Phone_Number;

                //usersDal.User.Add(req);
                //usersDal.Entry(req).State = System.Data.Entity.EntityState.Modified;
                usersDal.SaveChanges();
            }
            if (Session["Log"] == null)
            {
                return(RedirectToAction("Login", "Home"));
            }
            else
            {
                UsersDal usersDal  = new UsersDal();
                string   email     = Session["Log"].ToString();
                Users    connected = usersDal.User.Where(d => d.Email == email).First();

                List <Users> dbuser = (from x in usersDal.User where x.Email.Equals(email) select x).ToList();

                return(View(dbuser[0]));
            }
        }
示例#4
0
        /// <summary>
        /// Get the canonical user object from the Users DAL if it exists. Otherwise, creates an empty user with safe default
        /// values.
        /// </summary>
        /// <param name="userId">
        /// The ID of the user to load.
        /// </param>
        /// <return>
        /// The User Object
        /// </return>
        protected Users.Dal.DataModel.User RetrieveUser(Guid userId)
        {
            // Attempt to load the user from the Users DAL.
            Users.Dal.DataModel.User user = UsersDal.GetUserByUserId(userId);

            // Set safe default values if canonical user object does not exist or is not fully populated.
            if (user == null)
            {
                user = new Users.Dal.DataModel.User();
            }

            if (user.Name == null)
            {
                user.Name = String.Empty;
            }

            if (user.Email == null)
            {
                user.Email = String.Empty;
            }

            // Place only first name in salutation. If there is no name, make sure no space will be added.
            string[] nameParts = user.Name.Split(' ');
            SalutationName = String.Format(" {0}", nameParts[0]);
            if (SalutationName == " ")
            {
                SalutationName = String.Empty;
            }

            return(user);
        }
示例#5
0
        /// <summary>
        /// The register services.
        /// </summary>
        /// <param name="container">
        /// The container.
        /// </param>
        private void RegisterServices(IUnityContainer container)
        {
            EmailsBasePath = this.GetMandatorySetting(EmailsBasePathSetting);
            string storageAccount                 = this.GetMandatorySetting(StorageSetting);
            string emailJobsQueueName             = this.GetMandatorySetting(EmailJobsQueueNameSetting);
            string userDalConnectionString        = CloudConfigurationManager.GetSetting(UsersDalConnectionStringSetting);
            bool   isDebugSecurityProviderEnabled = bool.Parse(this.GetMandatorySetting(DebugSecurityProviderEnabled));
            Uri    bingOffersBaseUri              = new Uri(this.GetMandatorySetting(BingOffersBasePathUriSetting));

            // Read Email Confirmation Settings
            EntityConfirmationSettings entityConfirmationSettings = new EntityConfirmationSettings
            {
                BingOffersBaseUri = bingOffersBaseUri
            };

            var      emailJobsQueue         = new JobsQueue <EmailCargo>(storageAccount, emailJobsQueueName);
            var      priorityEmailJobsQueue = new PriorityEmailJobsQueue <PriorityEmailCargo>(storageAccount);
            UsersDal usersDal = new UsersDal(userDalConnectionString, queue: priorityEmailJobsQueue);

            container.RegisterInstance(entityConfirmationSettings);
            container.RegisterInstance <IJobsQueue <EmailCargo> >(emailJobsQueue);
            container.RegisterInstance <IPriorityEmailJobsQueue <PriorityEmailCargo> >(priorityEmailJobsQueue);
            container.RegisterInstance <IUsersDal>(usersDal);
            container.RegisterInstance <IEmailClient>(new EmailSendGridClient());

            // Authentication Modules
            // Add modules that perform authorization
            if (isDebugSecurityProviderEnabled)
            {
                Security.Add("user_debug", new UserDebugSecurityProvider(usersDal));
            }

            Security.Add("lomo", new LomoSecurityProvider(usersDal));
        }
示例#6
0
        public ActionResult CheckLogin(Users obj)
        {
            string       email  = Request.Form["email"];
            UsersDal     udal   = new UsersDal();
            List <Users> dbuser = (from x in udal.User where x.Email.Equals(obj.Email) select x).ToList();

            if (dbuser.Count == 0)
            {
                ViewBag.Error = "You arent registered, Register you before!";
                return(View("Register"));
            }
            else
            {
                if (obj.Password != dbuser[0].Password)
                {
                    ViewBag.Error = "password Wrong";
                    return(View("Login", obj));
                }

                Session["Log"]  = dbuser[0].Email;
                Session["Type"] = dbuser[0].type;

                return(RedirectToAction("Index", "Home"));
            }
        }
示例#7
0
        /// <summary>
        /// Starts the job fetcher
        /// </summary>
        public static void Start()
        {
            Log.Verbose("Starting EmailJob Fetcher");

            int fetchIntervalVal;

            if (int.TryParse(CloudConfigurationManager.GetSetting(MerchantEmailJobFetchIntervalInMinutes), out fetchIntervalVal))
            {
                _merchantEmailJobsFetchInterval = fetchIntervalVal * 60 * 1000;
            }
            else
            {
                _merchantEmailJobsFetchInterval = 60 * 60 * 1000;
            }

            _transactionReportSubject  = CloudConfigurationManager.GetSetting(MerchantTransactionReportSubject);
            _transactionReportCampaign = CloudConfigurationManager.GetSetting(MerchantTransactionReportCampaign);
            string storageAccount          = CloudConfigurationManager.GetSetting(StorageSetting);
            string emailJobsQueueName      = CloudConfigurationManager.GetSetting(EmailJobsQueueNameSetting);
            string userDalConnectionString = CloudConfigurationManager.GetSetting(UsersDalConnectionStringSetting);

            Log.Verbose("Finished reading settings");

            _usersDal       = new UsersDal(userDalConnectionString);
            _emailJobsQueue = new JobsQueue <EmailCargo>(storageAccount, emailJobsQueueName);

            Log.Verbose("Instantiated Users dal and Email Jobs queue");

            _merchantJobtimer = new Timer(callback => GetJob(), null, 0, _merchantEmailJobsFetchInterval);

            Log.Verbose("Created merchant email jobs timer with the interval set to {0} minutes", _merchantEmailJobsFetchInterval.ToString());
        }
示例#8
0
        /// <summary>
        /// 添加一条记录
        /// </summary>
        public ResultSet Add(Users entity)
        {
            Func <Users, ResultStatus> validate = (_entity) =>
            {
                return(new ResultStatus());
            };

            Func <Users, ResultStatus> op = (_entity) =>
            {
                int ret = new UsersDal().Add(entity);
                if (ret > 0)
                {
                    return(new ResultStatus());
                }
                else
                {
                    return new ResultStatus()
                           {
                               Success     = false,
                               Code        = StatusCollection.AddFailed.Code,
                               Description = StatusCollection.AddFailed.Description
                           }
                };
            };

            return(HandleBusiness(entity, op, validate));
        }
示例#9
0
        public ActionResult SubmitLogin(User user)
        {
            UsersDal    dal    = new UsersDal();
            List <User> users  = dal.users.ToList <User>();
            Encryption  enc    = new Encryption();
            bool        exists = false;

            foreach (User u in users)
            {
                if (u.username == user.username && enc.ValidatePassword(user.password, u.password))
                {
                    exists = true;
                    break;
                }
            }
            if (exists == true)
            {
                FormsAuthentication.SetAuthCookie("cookie", true);
                Session["username"]     = user.username;
                Session["loggedOn"]     = "true";
                TempData["LoginStatus"] = null;
                Session["userType"]     = "user";
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                TempData["LoginStatus"] = "Username or Password are incorrect.";
                return(View("UserLogin", user));
            }
        }
示例#10
0
        public ActionResult SubmitSignup()//action result for submiiting signup form
        {
            Users    userobj = new Users();
            UsersDal dal     = new UsersDal();

            userobj.FirstName    = Request.Form["User.FirstName"];
            userobj.LastName     = Request.Form["User.LastName"];
            userobj.UserPN       = Request.Form["User.UserPN"];
            userobj.UserName     = Request.Form["User.UserName"];
            userobj.UserEmail    = Request.Form["User.UserEmail"];
            userobj.UserPassword = Request.Form["User.UserPassword"];
            if (ModelState.IsValid)
            {
                dal.users.Add(userobj);
                try
                {
                    dal.SaveChanges();
                }
                catch (DbUpdateException)
                {
                    UsersVM passthis = new UsersVM(); //expecting for key violation exception coused by trying to signup with username which alrady exists
                    passthis.user = userobj;
                    dal.users.Remove(userobj);
                    ViewBag.username = "******";
                    return(View("Signup", passthis));//recalling signup view and passing the information user submitted to the form
                }
            }
            return(View("../Home/ShowHomePage", (new ProductsVM()
            {
                products_list = (new ProductsDal().products.ToList())
            })));                                                                                                             //returns to home page and loading products if sign up succeded
        }
示例#11
0
        public ActionResult Verify()//action result for logging in
        {
            string       rcvUserName = Request.Form["user.UserName"];
            string       rcvPassword = Request.Form["user.UserPassword"];
            UsersDal     dal         = new UsersDal();
            List <Users> usrobj      =
                (from y in dal.users
                 where y.UserName.Equals(rcvUserName)
                 select y).ToList <Users>();

            if (usrobj.Count > 0 && usrobj[0].UserPassword == rcvPassword) //checks for password equality in db
            {
                AdminDal     adal      = new AdminDal();
                List <Admin> adminlist = (from x in adal.admin where x.AUserName.Equals(rcvUserName) select x).ToList <Admin>();//checking if loged user is admin
                if (adminlist.Count > 0)
                {
                    Session["isadmin"] = true;
                }
                else
                {
                    Session["isadmin"] = false;
                }
                Session["signedin"] = usrobj[0];
                return(View("../Home/ShowHomePage", (new ProductsVM()
                {
                    products_list = (new ProductsDal().products.ToList())
                })));                                                      //returns to home page and loading products
            }
            ViewBag.message = "Wrong user name or password pls try again"; // the login form will check for that message if called
            return(View("Login"));
        }
        private async Task BlockUserAsync(IDialogContext context)
        {
            var users = (await UsersDal.GetUsersWithSpecificConditionAsync(x => !x.Block))
                        .Where(x => x.Id != context.Activity.From.Id).ToList();

            PromptDialog.Choice(context, BlockUserCallbackAsync, users.Select(x => x.Id),
                                "Select user which you want to block", descriptions: users.Select(x => x.Name));
        }
示例#13
0
        public ActionResult CoursesStudentsGrades()
        {
            /* Show all data */
            /* check if user had logged in */
            if (Session["ID"] == null || Session["password"] == null || Session["type"] == null)
            {
                return(RedirectToAction("Login", "Login"));
            }
            /* check if user is lecturer type */
            else if (!Session["type"].Equals("Faculty"))
            {
                return(RedirectToAction("Home", Session["type"].ToString()));
            }

            CoursesStudentsGrades viewobj = new CoursesStudentsGrades();

            viewobj.courses = new List <Course>();
            viewobj.users   = new List <User>();
            viewobj.grades  = new List <Grade>();

            using (CoursesDal coursesDb = new CoursesDal())
                using (UsersDal usersDb = new UsersDal())
                    using (GradesDal gradesDb = new GradesDal())
                    {
                        /* get all courses */
                        var courses =
                            (from row in coursesDb.Courses
                             orderby row.courseId
                             select row).ToList();

                        foreach (Course x in courses)
                        {
                            viewobj.courses.Add(x);
                        }

                        /* get all students */
                        var users =
                            (from row in usersDb.Users
                             where row.type.Equals("Student")
                             select row).ToList();
                        foreach (User x in users)
                        {
                            viewobj.users.Add(x);
                        }

                        /* get all grades */
                        var grades =
                            (from row in gradesDb.Grades
                             select row);

                        foreach (Grade x in grades)
                        {
                            viewobj.grades.Add(x);
                        }
                        return(View(viewobj));
                    }
        }
示例#14
0
        // GET: Chat
        public ActionResult Chat()
        {
            /* check if user had logged in */
            if (Session["ID"] == null || Session["password"] == null || Session["type"] == null)
            {
                return(RedirectToAction("Login", "Login"));
            }

            /* check if user is Faculty */
            else if (Session["type"].Equals("Faculty"))
            {
                /* get all valid user to send msg */
                using (UsersDal userdb = new UsersDal())
                {
                    UserList users = new UserList();
                    users.users = new List <User>();
                    foreach (var x in userdb.Users.Where(x => x.type.Equals("Lecturer") || x.type.Equals("Student")))
                    {
                        users.users.Add(x);
                    }
                    return(View(users));
                }
            }

            /* check if user is Lecturer */
            else if (Session["type"].Equals("Lecturer"))
            {
                /* get all valid user to send msg */
                using (UsersDal userdb = new UsersDal())
                {
                    UserList users = new UserList();
                    users.users = new List <User>();
                    foreach (var x in userdb.Users.Where(x => x.type.Equals("Faculty") || x.type.Equals("Student")))
                    {
                        users.users.Add(x);
                    }
                    return(View(users));
                }
            }

            /* user is student */
            else
            {
                /* get all valid user to send msg */
                using (UsersDal userdb = new UsersDal())
                {
                    UserList users = new UserList();
                    users.users = new List <User>();
                    foreach (var x in userdb.Users.Where(x => x.type.Equals("Lecturer") || x.type.Equals("Faculty")))
                    {
                        users.users.Add(x);
                    }
                    return(View(users));
                }
            }
        }
示例#15
0
        public void CreateUserTest()
        {
            UsersDTO test = new UsersDTO()
            {
                User_Id = 3, User_Login = "******"
            };
            UsersDal some_dal = new UsersDal("mongodb://localhost:27017/");
            var      User     = some_dal.CreateUser(test); //

            NUnit.Framework.Assert.IsTrue(User.User_Id > 0);
        }
示例#16
0
        private static void DeactivateSpamMailAddress(UsersDal usersDal)
        {
            int           count                = 0;
            int           deactivatedCount     = 0;
            List <string> sendGridInvalidUsers = new List <string>();

            sendGridInvalidUsers.AddRange(GetInvalidEmails("https://sendgrid.com/api/user.bounces.json?api_user=offersteam&api_key=123deals&user=offersteamtest&task=get&date=1"));
            sendGridInvalidUsers.AddRange(GetInvalidEmails("https://sendgrid.com/api/user.spamreports.json?api_user=offersteam&api_key=123deals&user=offersteamtest&task=get&date=1"));
            sendGridInvalidUsers.AddRange(GetInvalidEmails("https://sendgrid.com/api/user.invalidemails.json?api_user=offersteam&api_key=123deals&user=offersteamtest&task=get&date=1"));
            sendGridInvalidUsers.AddRange(GetInvalidEmails("https://sendgrid.com/api/blocks.get.json?api_user=offersteam&api_key=123deals&user=offersteamtest&task=get&date=1"));


            sendGridInvalidUsers.AddRange(GetInvalidEmails("https://sendgrid.com/api/bounces.get.json?api_user=offersteam&api_key=123deals&date=1"));
            sendGridInvalidUsers.AddRange(GetInvalidEmails("https://sendgrid.com/api/spamreports.get.json?api_user=offersteam&api_key=123deals&date=1"));
            sendGridInvalidUsers.AddRange(GetInvalidEmails("https://sendgrid.com/api/invalidemails.get.json?api_user=offersteam&api_key=123deals&date=1"));
            sendGridInvalidUsers.AddRange(GetInvalidEmails("https://sendgrid.com/api/blocks.get.json?api_user=offersteam&api_key=123deals&date=1"));

            Record(string.Format("Total invalid address from sendgrid: {0}", sendGridInvalidUsers.Count));

            foreach (var user in sendGridInvalidUsers)
            {
                count++;
                User userInfo = usersDal.GetUserByExternalId(user, UserExternalIdType.Email);
                if (userInfo != null && userInfo.MsId == null)
                {
                    var userSubscription = usersDal.GetEmailSubscriptionsByUserId(userInfo.Id, true);
                    if (userSubscription.Any())
                    {
                        foreach (var subscription in userSubscription)
                        {
                            if (subscription.IsActive)
                            {
                                usersDal.CreateOrUpdateEmailSubscription(new EmailSubscription
                                {
                                    IsActive         = false,
                                    LocationId       = subscription.LocationId,
                                    UserId           = subscription.UserId,
                                    SubscriptionType = subscription.SubscriptionType
                                });
                                deactivatedCount++;
                            }
                        }
                    }
                }

                if (count % 10 == 0)
                {
                    Record(string.Format("Processed {0} records", count));
                }
            }

            Record(string.Format("Total number of subscriptions deactivated : {0}", deactivatedCount));
        }
        private async Task AddAdminAsync(IDialogContext context)
        {
            var users = (await UsersDal.GetUsersWithSpecificConditionAsync(x => x.Role != Role.Admin)).ToList();

            if (users.Count == 0)
            {
                await context.PostAsync("Any user to promote");
                await StartAsync(context);
            }

            PromptDialog.Choice(context, AddAdminCallbackAsync, users.Select(x => x.Id),
                                "Select user which you want to promote", descriptions: users.Select(x => x.Name));
        }
        private async Task SendMessagesForAllNotBlockedUsersAsync(string text)
        {
            var users = await UsersDal.GetUsersWithSpecificConditionAsync(x => !x.Block);

            foreach (var user in users)
            {
                Activity activity = JsonConvert.DeserializeObject <Activity>(user.Activity);
                var      reply    = activity.CreateReply("");
                reply.Text = text;
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
        }
示例#19
0
        private static void CalculateEmailStatistics(UsersDal usersDal, string location)
        {
            object continuationContext = null;
            bool   hasMore             = true;
            string accessToken         = GetAnalyticsAccessToken();
            int    loggedIn            = 0;
            int    notLoggedIn         = 0;
            int    signedUp            = 0;
            int    addedCard           = 0;

            while (hasMore)
            {
                EmailsSubscriptionsBatchResponse response = usersDal.GetNextEmailSubscriptionsBatch(10000, true, continuationContext, SubscriptionType.WeeklyDeals);
                if (response.EmailSubscriptions != null)
                {
                    foreach (EmailSubscription emailSubscription in response.EmailSubscriptions)
                    {
                        if (emailSubscription.LocationId.Contains("us:postal:"))
                        {
                            Tuple <bool, string> tuple = CloHelper.IsCloRegion(emailSubscription.LocationId);
                            if (tuple.Item1 && String.Compare(location, tuple.Item2, StringComparison.CurrentCultureIgnoreCase) == 0)
                            {
                                User user = usersDal.GetUserByUserId(emailSubscription.UserId);
                                if (!String.IsNullOrEmpty(user.MsId))
                                {
                                    loggedIn++;
                                    Tuple <DateTime?, DateTime?> tuple1 = GetCloInfo(user.Id, accessToken);
                                    if (tuple1.Item1 != null)
                                    {
                                        signedUp++;
                                    }
                                    if (tuple1.Item2 != null)
                                    {
                                        addedCard++;
                                    }
                                }
                                else
                                {
                                    notLoggedIn++;
                                }
                            }
                        }
                    }
                }

                hasMore             = response.HasMore;
                continuationContext = response.ContinuationContext;
            }

            Debug.WriteLine("Total users {0}, Logged in {1}, Not Logged in {2}, Signed up {3}, Added card {4}", (loggedIn + notLoggedIn), loggedIn, notLoggedIn, signedUp, addedCard);
        }
示例#20
0
        /// <summary>
        /// 批量删除
        /// </summary>
        public ResultSet DeleteList(string where)
        {
            Func <string, ResultStatus> validate = (_where) =>
            {
                if (String.IsNullOrEmpty(_where))
                {
                    return new ResultStatus()
                           {
                               Code        = StatusCollection.ParameterError.Code,
                               Description = "参数 where 不能为空",
                               Success     = false
                           }
                }
                ;
                return(new ResultStatus());
            };

            Func <string, ResultStatus> op = (_where) =>
            {
                int ret = new UsersDal().DeleteList(_where);
                if (ret > 0)
                {
                    return(new ResultStatus());
                }
                else
                {
                    return new ResultStatus()
                           {
                               Success     = false,
                               Code        = StatusCollection.UpdateFailed.Code,
                               Description = StatusCollection.UpdateFailed.Description
                           }
                };
            };

            return(HandleBusiness(where, op, validate));
        }

        /// <summary>
        /// 获取 file max
        /// </summary>
        public double GetMaxField(string filed)
        {
            return(new UsersDal().GetMaxField(filed));
        }

        #endregion

        #region Extend
        #endregion
    }
示例#21
0
        private static void DispatchTrendingDeals(UsersDal usersDal, JobsQueue <EmailCargo> emailJobsQueue, bool includeList, List <Guid> userIds, string emailRenderingUrl, string campaignName, IEnumerable <Guid> dealIds)
        {
            string subject = ConfigurationManager.AppSettings["LoMo.TrendingDeals.Subject"];

            if (includeList)
            {
                foreach (Guid userId in userIds)
                {
                    Record(string.Format("Start dispatching. User Id={0}", userId));
                    var subscriptions = usersDal.GetEmailSubscriptionsByUserId(userId, true, SubscriptionType.WeeklyDeals.ToString());
                    foreach (EmailSubscription emailSubscription in subscriptions)
                    {
                        if (emailSubscription.LocationId.Contains("us:postal:"))
                        {
                            if (CloHelper.IsCloRegion(emailSubscription.LocationId).Item1)
                            {
                                DispatchEmailJob(emailSubscription, usersDal, emailJobsQueue, campaignName, emailRenderingUrl, true, null, dealIds: dealIds, subject: subject);
                            }
                        }
                    }
                }
            }
            else
            {
                object continuationContext = null;
                bool   hasMore             = true;
                while (hasMore)
                {
                    EmailsSubscriptionsBatchResponse response = usersDal.GetNextEmailSubscriptionsBatch(10000, true, continuationContext, SubscriptionType.WeeklyDeals);
                    if (response.EmailSubscriptions != null)
                    {
                        foreach (EmailSubscription emailSubscription in response.EmailSubscriptions)
                        {
                            if (userIds != null && userIds.Contains(emailSubscription.UserId))
                            {
                                Record(string.Format("User With Id {0} is excluded from this run.", emailSubscription.UserId));
                            }
                            else
                            {
                                if (emailSubscription.LocationId.Contains("us:postal:") && CloHelper.IsCloRegion(emailSubscription.LocationId).Item1)
                                {
                                    DispatchEmailJob(emailSubscription, usersDal, emailJobsQueue, campaignName, emailRenderingUrl, true, null, dealIds: dealIds, subject: subject);
                                }
                            }
                        }
                    }
                    hasMore             = response.HasMore;
                    continuationContext = response.ContinuationContext;
                }
            }
        }
        private async Task RemoveAdminAsync(IDialogContext context)
        {
            var users = (await UsersDal.GetUsersWithSpecificConditionAsync(x => x.Role == Role.Admin))
                        .Where(x => x.Id != context.Activity.From.Id).ToList();

            if (users.Count == 0)
            {
                await context.PostAsync("Any admins to demote");
                await StartAsync(context);
            }

            PromptDialog.Choice(context, RemoveAdminCallbackAsync, users.Select(x => x.Id),
                                "Select admin which you want to demote", descriptions: users.Select(x => x.Name));
        }
        private async Task UnblockUserAsync(IDialogContext context)
        {
            var users = (await UsersDal.GetUsersWithSpecificConditionAsync(x => x.Block)).ToList();

            if (users.Count == 0)
            {
                await context.PostAsync("Any blocked users found");
                await StartAsync(context);
            }
            else
            {
                PromptDialog.Choice(context, UnblockUserCallbackAsync, users.Select(x => x.Id),
                                    "Select user which you want to unblock", descriptions: users.Select(x => x.Name));
            }
        }
示例#24
0
        public ActionResult SubmitUser(User user)
        {
            if (ModelState.IsValid)
            {
                using (UsersDal userDb = new UsersDal())
                {
                    /* check if user exist */
                    var userInDb = (from row in userDb.Users
                                    where row.ID.Equals(user.ID)
                                    select row).FirstOrDefault();

                    /* if user exist */
                    if (userInDb != null)
                    {
                        /* check no attemp to change type */
                        if (user.type != userInDb.type)
                        {
                            TempData["msg"] = "Cant change user type";
                            return(View("AddUser", user));
                        }
                        /* update user */
                        userInDb.name     = user.name;
                        userInDb.lastName = user.lastName;
                        userInDb.password = user.password;
                        userDb.SaveChanges();
                        TempData["goodMsg"] = "Updated user";
                        /* redirect with succsees message */
                        return(View("AddUser", new User()));
                    }
                    /* add user */
                    else
                    {
                        userDb.Users.Add(user);
                        userDb.SaveChanges();
                        TempData["goodMsg"] = "Inserted user";
                        /* redirect with succsees message */
                        return(View("AddUser", new User()));
                    }
                }
            }
            else
            {
                return(View("AddUser", user));
            }
        }
示例#25
0
        private static void SuppressUsers(string filePath, UsersDal usersDal)
        {
            int count = 0;

            string[] lines = File.ReadAllLines(filePath);
            foreach (string line in lines)
            {
                usersDal.UpdateUserSuppressInfo(line, true);
                count++;

                if (count % 100 == 0)
                {
                    Console.WriteLine("Processed={0}", count);
                }
            }
            Console.WriteLine("Completed Processing. Processed={0}", count);
            Console.ReadLine();
        }
示例#26
0
        private static void DispatchNotificationMail(
            UsersDal usersDal,
            JobsQueue <EmailCargo> emailJobsQueue,
            string campaignName,
            string emailSubject,
            List <Guid> userIds)
        {
            int totalDispatched = 0;

            foreach (Guid userId in userIds)
            {
                User user = usersDal.GetUserByUserId(userId);
                EmailSubscription subscription = new EmailSubscription
                {
                    IsActive = true,
                    //Dummy location
                    LocationId       = "us:postal:00000",
                    SubscriptionType = SubscriptionType.Promotional,
                    UserId           = user.Id,
                };

                if (user.IsSuppressed == true)
                {
                    Record(
                        string.Format("User With Id={0} is suppressed", user.Id));
                }
                else
                {
                    totalDispatched++;
                    DispatchEmailJob(
                        subscription,
                        usersDal,
                        emailJobsQueue,
                        campaignName,
                        CampaignRenderingServiceURL,
                        false,
                        null,
                        false,
                        false,
                        emailSubject);
                    Record(string.Format("Total dispatched {0}", totalDispatched));
                }
            }
        }
        private async Task UnblockUserCallbackAsync(IDialogContext context, IAwaitable <string> userId)
        {
            var id   = await userId;
            var user = await UsersDal.GetUserByIdAsync(id);

            if (user == null)
            {
                await context.PostAsync("Selected user not found");
                await StartAsync(context);
            }
            else
            {
                user.Block = false;
                await UsersDal.UpdateUserAsync(user);

                await context.PostAsync("Selected user unblocked");
                await StartAsync(context);
            }
        }
        private async Task AddAdminCallbackAsync(IDialogContext context, IAwaitable <string> userId)
        {
            var id   = await userId;
            var user = await UsersDal.GetUserByIdAsync(id);

            if (user == null)
            {
                await context.PostAsync("Selected user not found");
                await StartAsync(context);
            }
            else
            {
                user.Role = Role.Admin;
                await UsersDal.UpdateUserAsync(user);

                await context.PostAsync("Selected user is admin");
                await StartAsync(context);
            }
        }
示例#29
0
        /// <summary>
        /// Gets the object to use to perform operations on users.
        /// </summary>
        /// <param name="commerceConfig">
        /// The CommerceConfig object to use to determine if mock partner dependencies are being used.
        /// </param>
        public static IUsersDal UsersDal(CommerceConfig commerceConfig)
        {
            if (commerceConfig == null)
            {
                throw new ArgumentNullException("commerceConfig", "Parameter commerceConfig cannot be null.");
            }

            if (usersDal == null)
            {
                usersDal = new UsersDal();

                if (commerceConfig.UseMockPartnerDependencies == true)
                {
                    usersDal = LateBinding.BuildObjectFromLateBoundAssembly <IUsersDal>("MockUsersDal",
                                                                                        LateBoundMocksAssemblyTypes);
                }
            }

            return(usersDal);
        }
示例#30
0
        private static void DispatchPromotionalMails(UsersDal usersDal, JobsQueue <EmailCargo> emailJobsQueue, List <Guid> userIds, string campaignName)
        {
            int count = 0;

            foreach (Guid userId in userIds)
            {
                Record(string.Format("Start dispatching. User Id={0}", userId));
                var subscriptions = usersDal.GetEmailSubscriptionsByUserId(userId, true, SubscriptionType.WeeklyDeals.ToString());
                foreach (EmailSubscription emailSubscription in subscriptions)
                {
                    if (emailSubscription.LocationId.Contains("us:postal:"))
                    {
                        DispatchEmailJob(emailSubscription, usersDal, emailJobsQueue, campaignName, CampaignRenderingServiceURL, false, null, false);
                        count++;
                    }
                }
            }

            Record(string.Format("Total mails sent : {0}", count));
        }
示例#31
0
 public void Login(HttpContext context)
 {
     var name = context.Request.Params["name"];
     var pwd = context.Request.Params["pwd"];
     var jzmm = context.Request.Params["jzmm"];
     context.Session["user"] = null;
     var usersDal = new UsersDal();
     try
     {
         var tmp = usersDal.Exist(new Users()
             {
                 LoginName = name,
                 Password = pwd
             });
         if (tmp)
         {
             context.Session["user"] = name;
             if (jzmm == "1")
             {
                 context.Session.Timeout = 60 * 24 * 7;//保存7天
             }
             _hashtable["isSuccess"] = true;
             _hashtable["jsMethod"] = "ajax_Login";
             var json = _jss.Serialize(_hashtable);
             context.Response.Write(json);
         }
         else
         {
             _hashtable["isSuccess"] = false;
             _hashtable["msg"] = "用户名或密码错误,请重新输入";
             var json = _jss.Serialize(_hashtable);
             context.Response.Write(json);
         }
     }
     catch (Exception e)
     {
         Log.Debug("出错原因:" + e.Message);
     }
 }
示例#32
0
 /// <summary>
 /// 修改密码
 /// </summary>
 /// <param name="context"></param>
 public void ModifyPassword(HttpContext context)
 {
     var usersDal = new UsersDal();
     var oldpass = context.Request.Params["oldpass"];
     var newpass = context.Request.Params["newpass"];
     var newpass2 = context.Request.Params["newpass2"];
     var user = context.Session["user"];
     if (user != null)
     {
         var data = usersDal.QueryUserInfo(user.ToString());
         var list = from da in data.AsEnumerable()
                    select new
                    {
                        name = da.Field<string>("name"),
                        loginname = da.Field<string>("loginname"),
                        password = da.Field<string>("password"),
                    };
         if (list.First().password != oldpass)
         {
             _hashtable["data"] = "msg";
             _hashtable["msg"] = "原始密码错误";
         }
         else
         {
             usersDal.ModifyPassword(new Users()
                 {
                     LoginName = user.ToString(),
                     Password = newpass
                 });
             _hashtable["data"] = "null";
         }
         _hashtable["isSuccess"] = true;
         context.Response.Write(_jss.Serialize(_hashtable));
     }
 }
示例#33
0
 /// <summary>
 /// 查找审核人、签发人 和编制人
 /// </summary>
 /// <param name="context"></param>
 public void QueryRiskNoticeRIB(HttpContext context)
 {
     var type = context.Request.Params["type"];
     try
     {
         var data = _riskNoticeRiDal.QueryRiskNoticeRI();
         var list = from da in data.AsEnumerable()
                    select new
                    {
                        openid = da.Field<string>("t_weixin"),
                        phonename = da.Field<string>("t_phonenum"),
                        name = da.Field<string>("t_name"),
                        type = da.Field<int>("t_type")
                    };
         _hashtable["data"] = list.ToList();
         if (type == "add")
         {
             var user = context.Session["user"].ToString();
             UsersDal usersDal = new UsersDal();
             var tmp = usersDal.QueryUserInfo(user);
             var listtmp = from t in tmp.AsEnumerable()
                           select new
                               {
                                   name = t.Field<string>("name")
                               };
             _hashtable["bzr"] = listtmp.ToList()[0].name;
         }
         if (type == "edit")
         {
             var id = context.Request.Params["id"];
             var data2 = _riskNoticeDal.QueryBzr(id);
             var bzr = from da2 in data2.AsEnumerable()
                       select new
                       {
                           bzr = da2.Field<string>("t_operator"),
                       };
             _hashtable["bzr"] = bzr.ToList();
         }
         _hashtable["jsMethod"] = "ajax_QueryRiskNoticeRIB";
         _hashtable["isSuccess"] = true;
         context.Response.Write(_jss.Serialize(_hashtable));
     }
     catch (Exception e)
     {
         _hashtable["isSuccess"] = false;
         context.Response.Write(_jss.Serialize(_hashtable));
         Log.Debug("出错原因:" + e.Message);
     }
 }
示例#34
0
 /// <summary>
 /// 根据登录名获取信息
 /// </summary>
 /// <param name="context"></param>
 public void QueryUserInfo(HttpContext context)
 {
     var usersDal = new UsersDal();
     var user = context.Session["user"];
     if (user != null)
     {
         var data = usersDal.QueryUserInfo(user.ToString());
         var list = from da in data.AsEnumerable()
                    select new
                        {
                            name = da.Field<string>("name"),
                            loginname = da.Field<string>("loginname"),
                            password = da.Field<string>("password"),
                        };
         _hashtable["data"] = list.ToList();
         _hashtable["isSuccess"] = true;
         _hashtable["jsMethod"] = "ajax_QueryUserInfo";
         context.Response.Write(_jss.Serialize(_hashtable));
     }
     else
     {
         _hashtable["data"] = "session";
         _hashtable["isSuccess"] = true;
         _hashtable["jsMethod"] = "ajax_QueryUserInfo";
         context.Response.Write(_jss.Serialize(_hashtable));
     }
 }