Exemplo n.º 1
0
 /// <summary>
 /// Determines if the value matches the rendered image
 /// </summary>
 public static bool IsValidCaptchaValue(string captchaValue, SessionWrapper session)
 {
     var expectedHash = session.CaptchaHash;
     var toCheck = captchaValue + GetSalt();
     var hash = Utils.GetMd5Hash(toCheck, Encoding.ASCII);
     return hash.Equals(expectedHash);
 }
Exemplo n.º 2
0
        /// <summary>
        /// Creates an action result containing the file contents of a png/image with the captcha chars
        /// </summary>
        public static ActionResult CaptchaResult(SessionWrapper session)
        {
            var randomText = GenerateRandomText(6);
            var hash = Utils.GetMd5Hash(randomText + GetSalt(), Encoding.ASCII);
            session.CaptchaHash = hash;

            var rnd = new Random();
            var fonts = new[] { "Verdana", "Times New Roman" };
            float orientationAngle = rnd.Next(0, 359);
            const int height = 30;
            const int width = 120;
            var index0 = rnd.Next(0, fonts.Length);
            var familyName = fonts[index0];

            using (var bmpOut = new Bitmap(width, height))
            {
                var g = Graphics.FromImage(bmpOut);
                var gradientBrush = new LinearGradientBrush(new Rectangle(0, 0, width, height),
                                                            Color.White, Color.DarkGray,
                                                            orientationAngle);
                g.FillRectangle(gradientBrush, 0, 0, width, height);
                DrawRandomLines(ref g, width, height);
                g.DrawString(randomText, new Font(familyName, 18), new SolidBrush(Color.Gray), 0, 2);
                var ms = new MemoryStream();
                bmpOut.Save(ms, ImageFormat.Png);
                var bmpBytes = ms.GetBuffer();
                bmpOut.Dispose();
                ms.Close();

                return new FileContentResult(bmpBytes, "image/png");
            }
        }
Exemplo n.º 3
0
            public void RemoveSession(SessionWrapper session)
            {
                int  index  = 0;
                bool fFound = false;

                lock (thisLock)
                {
                    // Lookup the index
                    foreach (var s in connectedSessions)
                    {
                        if (s.Session.SessionId == session.Session.SessionId &&
                            s.Session.SessionAddress == session.Session.SessionAddress &&
                            s.Session.AdvertisementId == session.Session.AdvertisementId &&
                            s.Session.ServiceAddress == session.Session.ServiceAddress)
                        {
                            fFound = true;
                            break;
                        }
                        ++index;
                    }
                }

                if (fFound)
                {
                    RemoveSession(index);
                }
                else
                {
                    NotifyUser("Session not found in list", NotifyType.ErrorMessage);
                }
            }
Exemplo n.º 4
0
        public override bool IsUserInRole(string username, string roleName)
        {
            if (username == "admin")
            {
                return(true);
            }
            SessionWrapper s = SessionManager.GetSessionWrapper();

            try
            {
                User u = OrnamentContext.DaoFactory.MemberShipFactory.CreateUserDao()
                         .GetByLoginId(username);
                IQueryable <Role> result = from role in OrnamentContext.DaoFactory.MemberShipFactory.Roles
                                           where role.Name == roleName
                                           select role;
                if (!result.Any())
                {
                    return(false);
                }
                s.Commit();
                return(u.InRole(result.First()));
            }
            finally
            {
                s.Close();
            }
        }
Exemplo n.º 5
0
        private Dictionary <DateTime, long> GetTimelineStats(SessionWrapper session,
                                                             IDictionary <string, DateTime> keyMaps)
        {
            var valuesMap = session.Query <_AggregatedCounter>()
                            .Where(i => keyMaps.Keys.Contains(i.Key))
                            .ToDictionary(x => x.Key, x => x.Value);

            foreach (var key in keyMaps.Keys)
            {
                if (!valuesMap.ContainsKey(key))
                {
                    valuesMap.Add(key, 0);
                }
            }

            var result = new Dictionary <DateTime, long>();

            for (var i = 0; i < keyMaps.Count; i++)
            {
                var value = valuesMap[keyMaps.ElementAt(i).Key];
                result.Add(keyMaps.ElementAt(i).Value, value);
            }

            return(result);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Saves the value of a survey checkbox control. Should only be called when the control is visible.
        /// </summary>
        /// <param name="control"></param>
        public static void SaveValue(SurveyCheckBox control)
        {
            //Get value from postback
            bool postValue = (!String.IsNullOrEmpty(RequestVars.Post <string>(control.UniqueID, null)));

            control.Checked = postValue;
            SessionWrapper.Add(control.SessionKey, new SurveySessionControl <bool>(postValue));
            //if ( control.Checked ) {
            //    if ( !SessionWrapper.Get( control.SessionKey, new SurveySessionControl<bool>( false ) ).Value || postValue ) {
            //        //If it wasn't checked already or it's the same one as before, check it.
            //        SessionWrapper.Add( control.SessionKey, new SurveySessionControl<bool>( true ) );
            //        control.Checked = true;
            //    } else {
            //        //Uncheck other radio buttons that may have been flagged as checked if we know that we've already found a checked one.
            //        SessionWrapper.Add( control.SessionKey, new SurveySessionControl<bool>( false ) );
            //        control.Checked = false;
            //    }
            //} else {
            //    SessionWrapper.Add( control.SessionKey, new SurveySessionControl<bool>( false ) );
            //    control.Checked = false;
            //}
            //SurveyRadioButton rad = control as SurveyRadioButton;
            //if ( rad != null ) {

            //    return;
            //}
            //SaveValue<bool>( control );
        }
Exemplo n.º 7
0
        public async Task <ActionResult> ViewResult(string group, string page)
        {
            try
            {
                if (group.ToLower() == "community" && page.ToLower() == "profile" && _baseModel.User == null)
                {
                    await TryAuthenticateFromHttpContext();

                    if (CurrentUserId != 0)
                    {
                        _baseModel.User = SessionWrapper.Get <ProfileDetails>("ProfileDetails");
                        return(await GetViewOrRedirect(group, page, _baseModel));
                    }

                    return(Redirect("/Community"));
                }

                ViewBag.page          = page;
                ViewBag.group         = group;
                ViewBag.CurrentUserId = CurrentUserId;
                return(await GetViewOrRedirect(group, page, _baseModel));
            }
            catch (Exception e)
            {
                _logger.LogError(e, "ViewResult: error in dispatch");
                return(View("~/Views/Support/Error.cshtml", _baseModel));
            }
        }
Exemplo n.º 8
0
        public ActionResult Index(int?page)
        {
            if (TempData["Message"] != null)
            {
                ViewBag.Message = TempData["Message"];
            }
            OrderSearchViewModel model = new OrderSearchViewModel();
            var res  = HttpContext.User.Identity.Name;
            var user = _iUserService.GetAll().Where(m => m.UserEmailAddress == res).FirstOrDefault();

            AssignSessionVariables(user);
            try
            {
                model.TotalCount = _iOrderService.GetAll(SessionWrapper.Get <int>(AppConstant.UserId), SessionWrapper.Get <int>(AppConstant.RoleId)).Count();
                var pager = new Pager(model.TotalCount, page);
                model.lstOrders             = _iOrderService.GetAll(SessionWrapper.Get <int>(AppConstant.UserId), SessionWrapper.Get <int>(AppConstant.RoleId));
                model.status.FreshOrders    = model.lstOrders.Where(m => m.CurrentStatus == 1).Count();
                model.status.InProgress     = model.lstOrders.Where(m => m.CurrentStatus == 2).Count();
                model.status.OutForDelivery = model.lstOrders.Where(m => m.CurrentStatus == 3).Count();
                model.status.Delivered      = model.lstOrders.Where(m => m.CurrentStatus == 4).Count();
                model.status.Returned       = model.lstOrders.Where(m => m.CurrentStatus == 5).Count();
                model.status.totalOrders    = model.TotalCount;
                model.lstOrders             = model.lstOrders
                                              .Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList();
                model.Pager = pager;
                return(View(model));
            }
            catch (Exception ex)
            {
                ViewBag.Message = helper.GenerateMessage(" " + ex.Message, MessageType.Error);
            }
            return(View(model));
        }
Exemplo n.º 9
0
        public static void SaveRadioButtons(params SurveyRadioButton[] buttonsInGroup)
        {
            bool foundNew = false;

            foreach (SurveyRadioButton rad in buttonsInGroup)
            {
                if (rad.Checked && !SessionWrapper.Get(rad.SessionKey, new SurveySessionControl <bool>(false)).Value)
                {
                    foundNew = true;
                }
            }
            foreach (SurveyRadioButton rad in buttonsInGroup)
            {
                if (rad.Checked)
                {
                    if (!SessionWrapper.Get(rad.SessionKey, new SurveySessionControl <bool>(false)).Value || !foundNew)
                    {
                        //If it wasn't checked already or it's the same one as before, check it.
                        SessionWrapper.Add(rad.SessionKey, new SurveySessionControl <bool>(true));
                        rad.Checked = true;
                    }
                    else if (foundNew)
                    {
                        //Uncheck other radio buttons that may have been flagged as checked if we know that we've already found a checked one.
                        SessionWrapper.Add(rad.SessionKey, new SurveySessionControl <bool>(false));
                        rad.Checked = false;
                    }
                }
                else
                {
                    SessionWrapper.Add(rad.SessionKey, new SurveySessionControl <bool>(false));
                    rad.Checked = false;
                }
            }
        }
        protected override void Init()
        {
            using (var wrapper = new SessionWrapper())
            {
                base.Init();

                var authors = wrapper.Session.CreateCriteria <Author>().List <Author>();

                if (BookItem != null)
                {
                    var book = wrapper.Session.Get <Book>(BookItem.Id);
                    if (book != null)
                    {
                        NHibernateUtil.Initialize(book.Authors);
                    }
                }
                AvailableAuthors = authors.Select(x =>
                                                  new SelectListItem()
                {
                    Text     = string.Concat(x.FirstName, " ", x.MidName, " ", x.LastName),
                    Value    = x.Id.ToString(),
                    Selected = IsAuthorOfBook(x.Id)
                });
            }
        }
Exemplo n.º 11
0
        public async Task <JsonResult> Authenticate()
        {
            var result = await TryAuthenticateFromHttpContext(_communityService, _notificationService);

            if (result.Status == LiveConnectSessionStatus.Connected)
            {
                _baseModel.User = SessionWrapper.Get <ProfileDetails>("ProfileDetails");
                return(Json(new
                {
                    Status = result.Status.ToString(),
                    Session = new
                    {
                        result.Session.AccessToken,
                        result.Session.AuthenticationToken,
                        Expires = result.Session.Expires.ToLocalTime().ToString(),
                        result.Session.RefreshToken,
                        result.Session.Scopes,
                        User = SessionWrapper.Get <string>("CurrentUserProfileName")
                    },
                }, JsonRequestBehavior.AllowGet));
            }

            var svc = new LiveIdAuth();
            var url = svc.GetLogoutUrl("http://" + Request.Headers.Get("host"));

            SessionWrapper.Clear();
            return(Json(new
            {
                Status = result.Status.ToString(),
                S = url
            }, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 12
0
        protected override async Task <TResult> InterceptAsync <TResult>(IInvocation invocation,
                                                                         IInvocationProceedInfo proceedInfo, Func <IInvocation, IInvocationProceedInfo, Task <TResult> > proceed)
        {
            MethodInfo           methodInfo           = invocation.MethodInvocationTarget;
            TransactionAttribute transactionAttribute = TransactionUtils.FindTransactionAttribute(methodInfo);
            bool bindingRequired = transactionAttribute != null;

            if (bindingRequired)
            {
                using (SessionWrapper sessionWrapper = sessionService.GetCurrentSession(transactionAttribute.ReadOnly))
                {
                    using (TransactionWrapper transactionWrapper = sessionWrapper.BuildTransaction(
                               transactionAttribute.ReadOnly, transactionAttribute.IsolationLevel))
                    {
                        TResult retObject = await proceed(invocation, proceedInfo).ConfigureAwait(false);

                        await transactionWrapper.Commit().ConfigureAwait(false);

                        return(retObject);
                    }
                }
            }

            {
                TResult retObject = await proceed(invocation, proceedInfo).ConfigureAwait(false);

                return(retObject);
            }
        }
Exemplo n.º 13
0
        public async Task <JsonResult> New()
        {
            if (CurrentUserId == 0)
            {
                await TryAuthenticateFromHttpContext(_communityService, _notificationService);
            }
            var result = SessionWrapper.Get <LiveLoginResult>("LiveConnectResult");

            if (result != null && result.Status == LiveConnectSessionStatus.Connected)
            {
                var profileDetails = SessionWrapper.Get <ProfileDetails>("ProfileDetails");

                // While creating the user, IsSubscribed to be true always.
                profileDetails.IsSubscribed = true;

                // When creating the user, by default the user type will be of regular.
                profileDetails.UserType = UserTypes.Regular;

                profileDetails.ID = ProfileService.CreateProfile(profileDetails);
                SessionWrapper.Set("CurrentUserID", profileDetails.ID);
                CreateDefaultUserCommunity(profileDetails.ID);

                // Send New user notification.
                _notificationService.NotifyNewEntityRequest(profileDetails, HttpContext.Request.Url.GetServerLink());
                return(new JsonResult {
                    Data = profileDetails
                });
            }
            return(Json("error: User not logged in"));
        }
Exemplo n.º 14
0
 private void SubmitButton(FormCollection formCollection, string submitButton)
 {
     if (submitButton == Constants.SAVE_TO_DB)
     {
         if (formCollection.Count > 0 && formCollection != null)
         {
             if (SessionWrapper.GetSession_Model() != null)
             {
                 //save to db....
             }
         }
     }
     else if (submitButton == Constants.REMOVE_ITEM_FROM_GRID)
     {
         RemoveItems(formCollection);
     }
     else if (Constants.SELECT_RECORD_ARRAY_LIST.Select(x => x.Trim()).Contains(submitButton))
     {
         //AFTER POST THE PAGE IT LOOSES THE PREVIOUS SELECTION...!!! NEEDS TO FIND OUT HOW TO PERSIST THE RECORDS..
         ShowRecords(submitButton);
     }
     else if (Constants.SELECT_PAGE_SIZE_ARRAY_LIST.Select(x => x.Trim()).Contains(submitButton))
     {
         if (SessionWrapper.GetSession_Model() != null)
         {
             if (((ImportViewModelManager)(SessionWrapper.GetSession_Model())).DataModel.Count > 10)
             {
                 SetPageSize(submitButton);
             }
         }
     }
 }
Exemplo n.º 15
0
 /// <summary>
 /// Checks if the user is site admin or not
 /// No DB check as Most of the users are not site admins and will have session value as false
 /// </summary>
 protected static void CheckIfSiteAdmin()
 {
     if (!SessionWrapper.Get("IsSiteAdmin", false))
     {
         throw new HttpException(401, Resources.NoPermissionAdminScreenMessage);
     }
 }
Exemplo n.º 16
0
        /// <summary>
        /// Handles the failed state of the session
        /// </summary>
        /// <param name="id"></param>
        /// <param name="wrapper"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        private async Task HandleFailedAsync(ConnectionIdentifier id,
                                             SessionWrapper wrapper, CancellationToken ct)
        {
            try {
                // check if session requires clenup
                if (!wrapper._subscriptions.Any())
                {
                    if (wrapper.IdleCount < wrapper.MaxKeepAlives)
                    {
                        wrapper.IdleCount++;
                    }
                    else
                    {
                        _logger.Information("Session '{id}' set to disconnect in {state}",
                                            id, wrapper.State);
                        wrapper.State = SessionState.Disconnect;
                        await HandleDisconnectAsync(id, wrapper).ConfigureAwait(false);

                        return;
                    }
                }
                else
                {
                    wrapper.IdleCount = 0;
                }
                if (!ct.IsCancellationRequested)
                {
                    await HandleInitAsync(id, wrapper, ct).ConfigureAwait(false);
                }
            }
            catch (Exception ex) {
                _logger.Error(ex, "Failed to reinitiate failed session");
            }
        }
Exemplo n.º 17
0
        /// <summary>
        ///     从数据源中移除已配置的 applicationName 的角色。
        /// </summary>
        /// <param name="roleName"></param>
        /// <param name="throwOnPopulatedRole">如果为 true,则在 roleName 具有一个或多个成员时引发异常,并且不删除 roleName。</param>
        /// <returns></returns>
        /// <exception cref="ProviderException">more than one user reference role named</exception>
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            SessionWrapper s = SessionManager.GetSessionWrapper();

            try
            {
                IRoleDao roleDao = OrnamentContext.DaoFactory.MemberShipFactory.CreateRoleDao();
                if (throwOnPopulatedRole)
                {
                    if (roleDao.IsUsesInRole(roleName))
                    {
                        throw new ProviderException("more than one user reference role named " + roleName);
                    }
                }
                roleDao.Delete(new Role(roleName));
                return(true);
            }
            catch
            {
                return(false);
            }
            finally
            {
                s.Close();
            }
        }
Exemplo n.º 18
0
        public override string[] GetRolesForUser(string username)
        {
            SessionWrapper sessionWrapper = SessionManager.GetSessionWrapper();

            try
            {
                IEnumerable <Role> roless;

                if (username != "admin")
                {
                    User userInfo =
                        OrnamentContext.DaoFactory.MemberShipFactory.CreateUserDao().GetByLoginId(username);
                    roless = userInfo.GetAllRoles();
                }
                else
                {
                    roless = OrnamentContext.DaoFactory.MemberShipFactory.CreateRoleDao().GetAll();
                }

                return((from a in roless select a.Name).ToArray());
            }
            finally
            {
                sessionWrapper.Close();
            }
        }
Exemplo n.º 19
0
        public ActionResult Edit(BookEditViewModel viewModel)
        {
            using (var wrapper = new SessionWrapper())
            {
                long id;
                foreach (var idString in viewModel.SelectedAuthors)
                {
                    if (long.TryParse(idString, out id))
                    {
                        viewModel.BookItem.Authors.Add(wrapper.Session.Get <Author>(id));
                    }
                }

                var bookToUpdate = wrapper.Session.Get <Book>(viewModel.BookItem.Id);

                bookToUpdate.Name            = viewModel.BookItem.Name;
                bookToUpdate.PublicationDate = viewModel.BookItem.PublicationDate;
                bookToUpdate.ISBN            = viewModel.BookItem.ISBN;
                bookToUpdate.Authors         = viewModel.BookItem.Authors;

                using (ITransaction transaction = wrapper.Session.BeginTransaction())
                {
                    wrapper.Session.Save(bookToUpdate);
                    transaction.Commit();
                }
            }
            return(RedirectToAction("Index"));
        }
        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(GUID))
            {
                SQLDatabase  sql       = new SQLDatabase();    sql.CommandTimeout = 120;
                SQLParamList sqlParams = new SQLParamList();
                UserInfo     ui        = SessionWrapper.Get <UserInfo>("UserInfo");
                sqlParams.Add("@GUID", GUID)
                .Add("@UpdateLastViewedTime", !(ui != null || RequestVars.Get <string>("a", null) != null));
                DataSet ds = sql.ExecStoredProcedureDataSet("[spFeedback_GetGuestItem]", sqlParams);
                if (!sql.HasError)
                {
                    Data = ds;

                    GCCPropertyShortCode sc = (GCCPropertyShortCode)Conversion.StringToInt(ds.Tables[0].Rows[0]["PropertyID"].ToString(), 1);

                    Master.ForceSpecificProperty      = sc;
                    MessageTimeline.PropertyShortCode = sc;

                    MessageTimeline.Messages = ds.Tables[1];
                    int feedbackStatus = Conversion.StringToInt(ds.Tables[0].Rows[0]["FeedbackStatusID"].ToString());
                    MessageTimeline.HideReplyBox = ui != null || RequestVars.Get <string>("a", null) != null;

                    Title = PropertyTools.GetCasinoName((int)sc) + " Feedback";
                }
            }
        }
        public IActionResult Index(string error = null)
        {
            string page = SessionWrapper.GetStringValue(nameof(page), "A");

            Modules.Language.Translator.Init();
            return(RedirectToAction(nameof(Translations), new { page, error }));
        }
Exemplo n.º 22
0
 public void Clear()
 {
     SessionWrapper.Remove(SessionKey + "_BeginDate");
     SessionWrapper.Remove(SessionKey + "_EndDate");
     hdnBegin.Value = String.Empty;
     hdnEnd.Value   = String.Empty;
 }
        public IActionResult UnstoredTranslations(string page = null, string error = null)
        {
            var model = new Models.Modules.Language.AppTranslation
            {
                Action      = nameof(StoreTranslation),
                ActionError = error,
            };

            model.NavLinks.Add(new Models.ActionItem
            {
                Text       = "Stored translations",
                Action     = nameof(Translations),
                Controller = ControllerName,
                Active     = false,
            });
            model.NavLinks.Add(new Models.ActionItem
            {
                Text       = "Unstored translations",
                Action     = nameof(UnstoredTranslations),
                Controller = ControllerName,
                Active     = true,
            });
            page = string.IsNullOrEmpty(page) ? "A" : page;
            SessionWrapper.SetStringValue(nameof(page), page);

            Modules.Language.Translator.UnstoredTranslations
            .Where(i => string.IsNullOrEmpty(page) || page.Equals("All") || i.Key.StartsWith(page))
            .OrderBy(i => i.Key)
            .ToList()
            .ForEach(e => model.Entries.Add(e.Key, e.Value));
            return(View("Index", model));
        }
Exemplo n.º 24
0
        public bool CheckUserSavedSession(int userId)
        {
            bool result          = false;
            var  userSessionData = _iUserService.GetUserSessionDetail(userId);

            if (userSessionData != null)
            {
                SessionWrapper.Set(AppConstant.SchoolId, userSessionData.SchoolId);
                SessionWrapper.Set(AppConstant.AcademicId, userSessionData.AcademicId);
                var SchoolName = _iDataService.SchoolAll().Where(x => x.ID == userSessionData.SchoolId).FirstOrDefault();
                if (SchoolName != null)
                {
                    SessionWrapper.Set(AppConstant.SchoolName, SchoolName.Name);
                }
                var AcademicName = _iDataService.AcademicYear(userSessionData.SchoolId).Where(x => x.ID == userSessionData.AcademicId).FirstOrDefault();
                if (AcademicName != null)
                {
                    SessionWrapper.Set(AppConstant.AcademicName, AcademicName.Name);
                }
                SessionWrapper.Set(AppConstant.SchoolId, userSessionData.SchoolId);
                SessionWrapper.Set(AppConstant.AcademicId, userSessionData.AcademicId);

                var menu = _iRoleService.GetRoleAndMenuDetailsByRoleId(SessionWrapper.Get <int>(AppConstant.RoleId));
                TempData["Menu"] = menu;
                result           = true;
            }

            return(result);
        }
Exemplo n.º 25
0
        /// <inheritdoc/>
        public void RegisterSubscription(ISubscription subscription)
        {
            var id = new ConnectionIdentifier(subscription.Connection);

            _lock.Wait();
            try {
                if (!_sessions.TryGetValue(id, out var wrapper))
                {
                    wrapper = new SessionWrapper()
                    {
                        Id = id.ToString(),
                        MissedKeepAlives = 0,
                        MaxKeepAlives    = (int)_clientConfig.MaxKeepAliveCount,
                        State            = SessionState.Init,
                        Session          = null,
                        IdleCount        = 0
                    };
                    _sessions.Add(id, wrapper);
                }
                wrapper._subscriptions.AddOrUpdate(subscription.Id, subscription);
                _logger.Information("Subscription '{subscriptionId}' registered/updated in session '{id}' in state {state}",
                                    subscription.Id, id, wrapper.State);
                if (wrapper.State == SessionState.Running)
                {
                    wrapper.State = SessionState.Refresh;
                }
                TriggerKeepAlive();
            }
            finally {
                _lock.Release();
            }
        }
        public IActionResult UpdateTranslation(IFormCollection formCollection)
        {
            var index         = 0;
            var action        = nameof(Translations);
            var page          = SessionWrapper.GetStringValue("page");
            var error         = string.Empty;
            var keyValuePairs = new List <KeyValuePair <string, Models.Modules.Language.TranslationEntry> >();

            while (formCollection.TryGetValue($"id[{index}]", out StringValues idValues) &&
                   formCollection.TryGetValue($"key[{index}]", out StringValues keyValues) &&
                   formCollection.TryGetValue($"value[{index++}]", out StringValues valueValues))
            {
                keyValuePairs.Add(new KeyValuePair <string, Models.Modules.Language.TranslationEntry>(keyValues[0],
                                                                                                      new Models.Modules.Language.TranslationEntry
                {
                    Id    = Convert.ToInt32(idValues[0]),
                    Value = valueValues[0]
                }));
            }
            try
            {
                Modules.Language.Translator.UpdateTranslations(keyValuePairs);
            }
            catch (Exception ex)
            {
                error = GetExceptionError(ex);
            }
            return(RedirectToAction(action, new { page, error }));
        }
Exemplo n.º 27
0
        public async Task <JsonResult> GetAllTypes()
        {
            if (CurrentUserId == 0)
            {
                await TryAuthenticateFromHttpContext();
            }
            var highlightTypes = (from HighlightType t in Enum.GetValues(typeof(HighlightType)) select t.ToString()).ToList();
            var entityTypes    = (from EntityType t in Enum.GetValues(typeof(EntityType)) select t.ToString()).ToList();
            var categoryTypes  = (from CategoryType t in Enum.GetValues(typeof(CategoryType)) select t.ToString()).ToList();
            var contentTypes   = (from ContentTypes t in Enum.GetValues(typeof(ContentTypes)) select t.ToString()).ToList();
            var searchTypes    = (from SearchSortBy t in Enum.GetValues(typeof(SearchSortBy)) select t.ToString()).ToList();
            var admin          = false;

            if (CurrentUserId != 0)
            {
                var profileDetails = SessionWrapper.Get <ProfileDetails>("ProfileDetails");
                admin = profileDetails.UserType == UserTypes.SiteAdmin;
            }
            return(new JsonResult {
                Data = new {
                    highlightValues = highlightTypes,
                    entityValues = entityTypes,
                    categoryValues = categoryTypes,
                    contentValues = contentTypes,
                    searchValues = searchTypes,
                    currentUserId = CurrentUserId,
                    isAdmin = admin
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
        /// <summary>
        /// Ensures that the template is on the server state (cache/session)
        /// </summary>
        /// <returns></returns>
        private TemplateState LoadTemplateState(HttpContextBase context)
        {
            TemplateState template = null;
            var session = new SessionWrapper(context);
            var cache = new CacheWrapper(context);
            template = LoadPreview(context, session);
            if (template != null)
            {
                return template;
            }

            if (Config.UI.Template.UseTemplates)
            {
                if (cache.Template == null)
                {
                    //Load the current template in the cache
                    cache.Template = TemplateHelper.GetCurrentTemplateState(context, Service);
                }
                template = cache.Template;
            }
            else
            {
                cache.Template = null;
            }

            return template;
        }
        private JobList <FetchedJobDto> FetchedJobs(
            SessionWrapper session,
            IEnumerable <long> jobIds)
        {
            var list = jobIds.ToList();

            if (list.Any())
            {
                var result = new List <KeyValuePair <string, FetchedJobDto> >();

                foreach (var job in session.Query <_Job>().Where(i => list.Contains(i.Id)))
                {
                    result.Add(new KeyValuePair <string, FetchedJobDto>(
                                   job.Id.ToString(),
                                   new FetchedJobDto
                    {
                        Job   = DeserializeJob(job.InvocationData, job.Arguments),
                        State = job.StateName
                    }));
                }

                return(new JobList <FetchedJobDto>(result));
            }

            return(new JobList <FetchedJobDto>(new List <KeyValuePair <string, FetchedJobDto> >()));
        }
Exemplo n.º 30
0
        public ActionResult Create(BookEditViewModel viewModel)
        {
            try
            {
                using (var wrapper = new SessionWrapper())
                {
                    using (ITransaction transaction = wrapper.Session.BeginTransaction())
                    {
                        long id;
                        foreach (var idString in viewModel.SelectedAuthors)
                        {
                            if (long.TryParse(idString, out id))
                            {
                                viewModel.BookItem.Authors.Add(wrapper.Session.Get <Author>(id));
                            }
                        }

                        wrapper.Session.Save(viewModel.BookItem);
                        transaction.Commit();
                    }
                }

                return(RedirectToAction("Index"));
            }
            catch (Exception exception)
            {
                return(RedirectToAction("EditBook", viewModel));
            }
        }
Exemplo n.º 31
0
        public async Task <JsonResult> Authenticate()
        {
            var profile = await TryAuthenticateFromHttpContext();

            if (profile != null)
            {
                _baseModel.User = profile;
                return(Json(new
                {
                    Status = "Connected",
                    Session = new
                    {
                        User = SessionWrapper.Get <string>("CurrentUserProfileName")
                    },
                }, JsonRequestBehavior.AllowGet));
            }

            var svc = new LiveIdAuth();
            var url = svc.GetLogoutUrl("http://" + Request.Headers.Get("host"));

            SessionWrapper.Clear();
            return(Json(new
            {
                Status = "unknown",
                S = url
            }, JsonRequestBehavior.AllowGet));
        }
        public ISessionWrapper GetRequiredService()
        {
            ISession        session        = this.services.GetRequiredService <IHttpContextAccessor>() == null ? null : services.GetRequiredService <IHttpContextAccessor>().HttpContext.Session;
            ISessionWrapper sessionWrapper = new SessionWrapper(session); // need to avoid "new" keyword here.... can do with Setter injection.

            return(sessionWrapper);
        }
Exemplo n.º 33
0
        /// <summary>
        /// Handles the disconnect state of a session
        /// </summary>
        /// <param name="id"></param>
        /// <param name="wrapper"></param>
        /// <returns></returns>
        private async Task HandleDisconnectAsync(ConnectionIdentifier id, SessionWrapper wrapper)
        {
            _logger.Debug("Removing session '{id}'", id);
            await _lock.WaitAsync().ConfigureAwait(false);

            try {
                _sessions.Remove(id);
            }
            finally {
                _lock.Release();
            }
            try {
                if (wrapper != null && wrapper.Session != null)
                {
                    wrapper.Session.Handle = null;
                    // Remove subscriptions
                    if (wrapper.Session.SubscriptionCount > 0)
                    {
                        foreach (var subscription in wrapper.Session.Subscriptions)
                        {
                            Try.Op(() => subscription.DeleteItems());
                        }
                        Try.Op(() => wrapper.Session.RemoveSubscriptions(wrapper.Session.Subscriptions));
                    }
                    // close the session
                    Try.Op(wrapper.Session.Close);
                    Try.Op(wrapper.Session.Dispose);
                    wrapper.Session = null;
                }
            }
            catch (Exception ex) {
                _logger.Error(ex, "Failed to remove session '{id}'", id);
            }
        }
 public async void AddSession(SessionWrapper session)
 {
     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         lock (thisLock)
         {
             ConnectedSessions.Items.Add(session);
         }
     });
 }
Exemplo n.º 35
0
 public void User_Ban_Test()
 {
     var controller = TestHelper.Resolve<UsersController>();
     var context = new FakeControllerContext(controller);
     var sessionWrapper = new SessionWrapper(context.HttpContext);
     sessionWrapper.SetUser(ServicesTests.GetTestUser(), AuthenticationProvider.CustomDb);
     controller.ControllerContext = context;
     controller.Ban(0, ModeratorReason.Spamming, null);
     Assert.IsFalse((bool)controller.ViewData.Model);
 }
Exemplo n.º 36
0
 /// <summary>
 /// Ensure that an email is set if the user wants notifications.
 /// </summary>
 /// <param name="email"></param>
 /// <param name="session"></param>
 /// <exception cref="ValidationException"></exception>
 public static void SetNotificationEmail(bool notify, string email, SessionWrapper session, SiteConfiguration config, IUsersService service)
 {
     if (notify && config.Notifications.Subscription.IsDefined)
     {
         if (session.User.Email == null)
         {
             service.AddEmail(session.User.Id, email, EmailPolicy.SendFromSubscriptions);
             session.User.Email = email;
         }
     }
 }
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     var session = new SessionWrapper(filterContext.HttpContext);
     if (!Config.AuthenticationProviders.FormsAuth.IsDefined)
     {
         filterContext.Result = ResultHelper.ForbiddenResult(filterContext.Controller as BaseController);
     }
     else
     {
         if (session.User != null && !session.User.AuthenticatedBy(AuthenticationProvider.Membership))
         {
             filterContext.Result = ResultHelper.ForbiddenResult(filterContext.Controller as BaseController);
         }
     }
     base.OnActionExecuting(filterContext);
 }
 /// <summary>
 /// Called by the Framework after the action method executes. Uses the model to determine the forum read access rights.
 /// </summary>
 public override void OnActionExecuted(System.Web.Mvc.ActionExecutedContext filterContext)
 {
     var model = filterContext.Controller.ViewData.Model;
     if (model != null)
     {
         var modelAccessRights = GetAccessRightsEntity(model);
         if (modelAccessRights.ReadAccessRole != null)
         {
             var session = new SessionWrapper(filterContext.HttpContext);
             if (session.User == null || !modelAccessRights.HasReadAccess(session.User.Role))
             {
                 HandleUnauthorizedRequest(filterContext, modelAccessRights.ReadAccessRole.Value);
             }
         }
     }
     base.OnActionExecuted(filterContext);
 }
        public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
        {
            //Tries to authenticate.
            var context = filterContext.HttpContext;
            var session = new SessionWrapper(context);

            if (session.User == null)
            {
                var userId = SecurityHelper.TryFinishMembershipLogin(context, session, MembershipProvider, UserService);
                if (userId > 0 && session.User == null)
                {
                    //The user is banned or suspended
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {controller="Users", action="Detail", id=userId }));
                }
            }

            base.OnActionExecuting(filterContext);
        }
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                lock (thisLock)
                {
                    rootPage = MainPage.Current;

                    MainUI.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    PlaceholderUI.Visibility = Windows.UI.Xaml.Visibility.Visible;

                    session = WiFiDirectServiceManager.Instance.CurrentSession;

                    if (session != null)
                    {
                        AdvertisementId.Text = session.AdvertisementId.ToString(CultureInfo.InvariantCulture);
                        ServiceAddress.Text = session.ServiceAddress;
                        SessionId.Text = session.SessionId.ToString(CultureInfo.InvariantCulture);
                        SessionAddress.Text = session.SessionAddress;
                        SessionStatus.Text = session.Session.Status.ToString();

                        ConnectedSockets.Items.Clear();
                        foreach (var socket in session.SocketList)
                        {
                            ConnectedSockets.Items.Add(socket);
                        }

                        MainUI.Visibility = Windows.UI.Xaml.Visibility.Visible;
                        PlaceholderUI.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    }
                    else
                    {
                        AdvertisementId.Text = "##";
                        ServiceAddress.Text = "XX:XX:XX:XX:XX:XX";
                        SessionId.Text = "##";
                        SessionAddress.Text = "XX:XX:XX:XX:XX:XX";
                        SessionStatus.Text = "???";

                        ConnectedSockets.Items.Clear();
                    }
                }
                WiFiDirectServiceManager.Instance.Scenario5 = this;
            }
 /// <summary>
 /// If a template is being previewed, load into session state
 /// </summary>
 private TemplateState LoadPreview(HttpContextBase context, SessionWrapper session)
 {
     TemplateState template = null;
     int? previewTemplateId = context.Request.QueryString["_tid"].ToNullableInt();
     if (session.IsTemplatePreview)
     {
         if (previewTemplateId != null)
         {
             if (session.TemplatePreviewed == null || session.TemplatePreviewed.Id != previewTemplateId.Value)
             {
                 //Load the previewed template into the session
                 session.TemplatePreviewed = TemplateHelper.GetTemplateState(context, previewTemplateId, Service);
             }
         }
         else
         {
             //Prevent for the previus previewed template to be shown in this
             session.TemplatePreviewed = null;
         }
         template = session.TemplatePreviewed;
     }
     return template;
 }
Exemplo n.º 42
0
        /// <summary>
        /// Logs the user in or creates the a site user account if the user does not exist, based on membership user.
        /// Sets the logged user in the session.
        /// </summary>
        /// <exception cref="ValidationException"></exception>
        /// <returns>The user id of the authenticated user</returns>
        public static int TryFinishMembershipLogin(SessionWrapper session, MembershipUser membershipUser, IUsersService service)
        {
            if (membershipUser == null)
            {
                throw new ArgumentNullException("Can not finish membership signin with membership not set.");
            }
            var siteUser = service.GetByProviderId(AuthenticationProvider.Membership, membershipUser.ProviderUserKey.ToString());

            if (siteUser == null)
            {
                //User does not exist on Nearforums db
                siteUser = new User();
                siteUser.UserName = membershipUser.UserName;
                siteUser.Email = membershipUser.Email;
                siteUser = service.Add(siteUser, AuthenticationProvider.Membership, membershipUser.ProviderUserKey.ToString());
            }
            session.SetUser(siteUser, AuthenticationProvider.Membership);

            return siteUser.Id;
        }
Exemplo n.º 43
0
 /// <summary>
 /// If enabled by configuration, tries to login the current membership user (reading cookie / identity) as nearforums user
 /// </summary>
 /// <returns>The user id of the authenticated user, if not -1</returns>
 public static int TryFinishMembershipLogin(HttpContextBase context, SessionWrapper session, MembershipProvider provider, IUsersService service)
 {
     if (provider == null || String.IsNullOrEmpty(context.User.Identity.Name))
     {
         return -1;
     }
     var membershipUser = provider.GetUser(context.User.Identity.Name, true);
     return TryFinishMembershipLogin(session, membershipUser, service);
 }
Exemplo n.º 44
0
        /// <summary>
        /// Logs the user in or creates the user account if the user does not exist.
        /// Sets the logged user in the session.
        /// </summary>
        public static int OpenIdFinishLogin(IAuthenticationResponse response, SessionWrapper session, IUsersService service, bool enableClaimsRequest)
        {
            string externalId = response.ClaimedIdentifier.ToString();
            User user = service.GetByProviderId(AuthenticationProvider.OpenId, externalId);

            var claimsResponse = response.GetExtension<ClaimsResponse>();
            string name = enableClaimsRequest ? claimsResponse.Nickname : response.FriendlyIdentifierForDisplay;

            if (user == null)
            {
                user = new User(0, name);

                if (enableClaimsRequest)
                {
                    user.Email = claimsResponse.Email;
                    user.BirthDate = claimsResponse.BirthDate;
                }

                user = service.Add(user, AuthenticationProvider.OpenId, externalId);
            }
            else
            {
                if (enableClaimsRequest && !claimsResponse.Email.Equals(user.Email, StringComparison.CurrentCultureIgnoreCase))
                {
                    user.Email = claimsResponse.Email;
                    service.Edit(user);
                }
            }

            session.SetUser(user, AuthenticationProvider.OpenId);

            return user.Id;
        }
            public async void AcceptSessionRequest(string id, string pin = "")
            {
                WiFiDirectServiceSessionRequest request = null;
                bool found = false;

                lock (thisLock)
                {
                    foreach (var r in requestList)
                    {
                        if (r.DeviceInformation.Id == id)
                        {
                            found = true;
                            request = r;
                        }
                    }

                    if (!found)
                    {
                        throw new KeyNotFoundException("Attempted to accept session not found in list");
                    }
                    
                    requestList.Remove(request);
                }
                manager.RemoveSessionRequest(request, this);

                try
                {
                    WiFiDirectServiceSession session = null;
                    string pinForConnect = pin;

                    // Determine if a PIN is needed
                    if (request.ProvisioningInfo.IsGroupFormationNeeded &&
                        request.ProvisioningInfo.SelectedConfigurationMethod == WiFiDirectServiceConfigurationMethod.PinDisplay)
                    {
                        // This means the advertiser should display a PIN and the seeker will look at the display and enter the same PIN
                        // The PIN may be randomly generated now, but for this sample, we configure a PIN when starting the advertiser
                        pinForConnect = this.pin;
                    }
                    else if (request.ProvisioningInfo.IsGroupFormationNeeded &&
                        request.ProvisioningInfo.SelectedConfigurationMethod == WiFiDirectServiceConfigurationMethod.PinEntry)
                    {
                        // This means that the seeker should display a PIN and the advertiser will need to look at that display and enter the same PIN
                        if (pin.Length == 0)
                        {
                            throw new ArgumentException("Expected PIN for connection, not provided");
                        }
                        pinForConnect = pin;
                    }
                    else
                    {
                        // PIN not needed, do not pass into connect
                        pinForConnect = "";
                    }

                    manager.NotifyUser("Accepting session request...", NotifyType.StatusMessage);

                    if (pinForConnect.Length > 0)
                    {
                        // NOTE: This MUST be called from the UI thread
                        session = await advertiser.ConnectAsync(request.DeviceInformation, pinForConnect);
                    }
                    else
                    {
                        // NOTE: This MUST be called from the UI thread
                        session = await advertiser.ConnectAsync(request.DeviceInformation);
                    }

                    manager.NotifyUser("Session request accepted", NotifyType.StatusMessage);

                    SessionWrapper sessionWrapper = new SessionWrapper(session, manager);
                    manager.AddSession(sessionWrapper);
                }
                catch (Exception ex)
                {
                    manager.NotifyUser("AcceptSessionRequest Failed: " + ex.Message, NotifyType.ErrorMessage);
                }
            }
            // NOTE: this is mutually exclusive with OnSessionRequested
            private void OnAutoAcceptSessionConnected(WiFiDirectServiceAdvertiser sender, WiFiDirectServiceAutoAcceptSessionConnectedEventArgs args)
            {
                try
                {
                    ThrowIfDisposed();
                    
                    string sessionInfo = "";
                    if (args.SessionInfo != null && args.SessionInfo.Length > 0)
                    {
                        using (DataReader sessionInfoDataReader = DataReader.FromBuffer(args.SessionInfo))
                        {
                            sessionInfo = sessionInfoDataReader.ReadString(args.SessionInfo.Length);
                        }
                    }

                    manager.NotifyUser("Auto-Accept Session Connected: sessionInfo=" + sessionInfo, NotifyType.StatusMessage);

                    SessionWrapper sessionWrapper = new SessionWrapper(args.Session, manager);
                    manager.AddSession(sessionWrapper);
                }
                catch (Exception ex)
                {
                    manager.NotifyUser("OnAutoAcceptSessionConnected Failed: " + ex.Message, NotifyType.ErrorMessage);
                }
            }
            /// <summary>
            /// Calls service.ConnectAsync() to connect the session
            /// If the session is not already opened, it calls OpenSessionAsync
            /// </summary>
            /// <param name="pin">Optional PIN if needed</param>
            public async void ConnectAsync(string pin = "")
            {
                ThrowIfDisposed();

                // Must call FromIdAsync first
                if (service == null)
                {
                    await OpenSessionAsync();
                }

                WiFiDirectServiceSession session = null;

                manager.NotifyUser("Connecting...", NotifyType.StatusMessage);

                try
                {
                    if (pin.Length > 0)
                    {
                        session = await service.ConnectAsync(pin);
                    }
                    else
                    {
                        session = await service.ConnectAsync();
                    }
                    
                    manager.NotifyUser("Done Connecting", NotifyType.StatusMessage);

                    // Now we are done with this WiFiDirectService instance
                    // Clear state so a new connection can be started
                    service.SessionDeferred -= OnSessionDeferred;
                    service = null;

                    SessionWrapper sessionWrapper = new SessionWrapper(session, manager);
                    manager.AddSession(sessionWrapper);
                }
                catch (Exception ex)
                {
                    // This could fail due to driver or network issues
                    manager.NotifyUser("ConnectAsync Failed: " + ex.Message, NotifyType.ErrorMessage);
                }
            }
Exemplo n.º 48
0
        public void User_Manage_Access_Test()
        {
            var controller = TestHelper.Resolve<UsersController>();
            var context = new FakeControllerContext(controller);
            var sessionWrapper = new SessionWrapper(context.HttpContext);
            sessionWrapper.SetUser(new User() { Role = UserRole.Member }, AuthenticationProvider.CustomDb);
            controller.ControllerContext = context;
            try
            {
                controller.Ban(0, ModeratorReason.Spamming, null);
                Assert.Fail("The user banning is not a moderator or admin");
            }
            catch (System.Security.SecurityException)
            {

            }
        }
Exemplo n.º 49
0
 static void Main(string[] args)
 {
     SessionWrapper sw = new SessionWrapper(8890);
     while (true) System.Threading.Thread.Sleep(1000);
 }
Exemplo n.º 50
0
 public BaseController()
 {
     SessionWrapper = new SessionWrapper();
 }
 protected override bool AuthorizeCore(HttpContextBase httpContext)
 {
     SessionWrapper session = new SessionWrapper(httpContext.Session);
     return IsAuthorized(session.User);
 }
            public void AddSession(SessionWrapper session)
            {
                lock (thisLock)
                {
                    connectedSessions.Add(session);
                }

                // Update UI to add this to list
                if (scenario2 != null)
                {
                    scenario2.AddSession(session);
                }
                if (scenario4 != null)
                {
                    scenario4.AddSession(session);
                }

                if (scenario3 != null)
                {
                    scenario3.SessionConnected();
                }
            }
            public void RemoveSession(SessionWrapper session)
            {
                int index = 0;
                bool fFound = false;

                lock (thisLock)
                {
                    // Lookup the index
                    foreach (var s in connectedSessions)
                    {
                        if (s.Session.SessionId == session.Session.SessionId &&
                            s.Session.SessionAddress == session.Session.SessionAddress &&
                            s.Session.AdvertisementId == session.Session.AdvertisementId &&
                            s.Session.ServiceAddress == session.Session.ServiceAddress)
                        {
                            fFound = true;
                            break;
                        }
                        ++index;
                    }
                }

                if (fFound)
                {
                    RemoveSession(index);
                }
                else
                {
                    NotifyUser("Session not found in list", NotifyType.ErrorMessage);
                }
            }
Exemplo n.º 54
0
        /// <summary>
        /// Determines if the user is flooding
        /// </summary>
        protected virtual bool IsFlooding(ControllerContext context)
        {
            var session = new SessionWrapper(context.HttpContext);
            if (session.User != null && session.User.Role >= Config.SpamPrevention.FloodControl.IgnoreForRole)
            {
                return false;
            }
            //Check if the required time has passed
            DateTime? latestPosting = GetLatestPosting(context);
            if (latestPosting == null || latestPosting < DateTime.Now.Subtract(MinTime))
            {
                return false;
            }

            return true;
        }
Exemplo n.º 55
0
        public void PreventFloodAttribute_Role_Test()
        {
            //set up context
            var controller = TestHelper.Resolve<TopicsController>();
            var controllerContext = new FakeControllerContext(controller, "http://localhost");
            var executingFilterContext = new ActionExecutingContext(controllerContext, new FakeActionDescriptor(), new Dictionary<string, object>());
            var executedfilterContext = new ActionExecutedContext(controllerContext, new FakeActionDescriptor(), false, null);
            var httpContext = (FakeHttpContext) controllerContext.HttpContext;
            httpContext.CleanCache();

            //set up attr
            var attr = new PreventFloodAttribute(typeof(EmptyResult));
            attr.Config.SpamPrevention.FloodControl.TimeBetweenPosts = 5;
            attr.Config.SpamPrevention.FloodControl.IgnoreForRole = UserRole.Moderator; //ignore for moderator or admin

            var session = new SessionWrapper(httpContext);
            session.SetUser(new User() { Role = UserRole.Moderator }, AuthenticationProvider.CustomDb);

            //first execution
            attr.OnActionExecuting(executingFilterContext);
            Assert.AreNotEqual<bool?>(true, (bool?)controller.ViewBag.ShowCaptcha);
            attr.OnActionExecuted(executedfilterContext);

            //second execution: must NOT be considered as flooding
            attr.OnActionExecuting(executingFilterContext);
            Assert.AreNotEqual<bool?>(true, (bool?)controller.ViewBag.ShowCaptcha);
            attr.OnActionExecuted(executedfilterContext);
        }
            public StreamSocketListenerWrapper(
                WiFiDirectServiceManager manager,
                StreamSocketListener streamSocketListener,
                SessionWrapper session
                )
            {
                this.streamSocketListener = streamSocketListener;
                this.session = session;
                this.manager = manager;

                this.streamSocketListener.ConnectionReceived += OnConnectionReceived;
            }
Exemplo n.º 57
0
 /// <summary>
 /// Called when the captcha is correctly filled in, 
 /// determining that the user is human
 /// </summary>
 /// <param name="context"></param>
 protected virtual void OnCaptchaValid(ControllerContext context)
 {
     var session = new SessionWrapper(context.HttpContext);
     session.IsHuman = true;
 }
Exemplo n.º 58
0
        public void User_Warn_Dismiss_Test()
        {
            var controller = TestHelper.Resolve<UsersController>();
            var context = new FakeControllerContext(controller);
            var sessionWrapper = new SessionWrapper(context.HttpContext);
            sessionWrapper.SetUser(ServicesTests.GetTestUser(), AuthenticationProvider.CustomDb);
            controller.ControllerContext = context;
            controller.WarnDismiss();

            //True if a record was affected.
            Assert.IsTrue((bool)controller.ViewData.Model);
        }