Exemplo n.º 1
0
 public ActionResult Active()
 {
     try
     {
         SiteState state = new SiteState(Url);
         StackyRepository repository = new StackyRepository(state);
         return View("Questions", new QuestionsModel(repository.GetQuestions(sortBy: QuestionSort.Activity, includeBody: true, page: state.Page, pageSize: state.PageSize), state));
     }
     catch (ApiException ex)
     {
         return View("Error", new HandleErrorInfo(ex, "Question", "Active"));
     }
 }
Exemplo n.º 2
0
        public ActionResult Question(int id)
        {
            try
            {
                SiteState state = new SiteState(Url);
                StackyRepository repository = new StackyRepository(state);
                Question question = repository.GetQuestion(id, true, true);
                IPagedList<Answer> answers = null;
                if (state.Page != 1)
                {
                    answers = repository.GetQuestionAnswers(id, page: state.Page, includeBody: true, includeComments: true);
                }

                return View(new QuestionModel(question, answers, state));
            }
            catch (ApiException ex)
            {
                return View("Error", new HandleErrorInfo(ex, "Question", "Active"));
            }
        }
Exemplo n.º 3
0
        public ActionResult Questions()
        {
            try
            {
                SiteState state = new SiteState(Url);
                StackyRepository repository = new StackyRepository(state);

                QuestionSort sort = QuestionSort.Hot;

                switch (state.Sort)
                {
                    case "Newest":
                        sort = QuestionSort.Newest;
                        break;
                    case "Featured":
                        sort = QuestionSort.Featured;
                        break;
                    case "Hot":
                        sort = QuestionSort.Hot;
                        break;
                    case "Votes":
                        sort = QuestionSort.Votes;
                        break;
                    case "Active":
                        sort = QuestionSort.Activity;
                        break;
                    default:
                        break;
                }

                return View(new QuestionsModel(repository.GetQuestions(sortBy: sort, includeBody: true, page: state.Page, pageSize: state.PageSize), state));
            }
            catch (ApiException ex)
            {
                return View("Error", new HandleErrorInfo(ex, "Question", "Active"));
            }
        }
Exemplo n.º 4
0
 public FileService(HttpClient http, SiteState siteState, IJSRuntime jsRuntime) : base(http)
 {
     _siteState = siteState;
     _jsRuntime = jsRuntime;
 }
Exemplo n.º 5
0
        public static IHtmlControl GetActualNewsBlock(SiteState state, LightObject currentUser)
        {
            IHtmlControl[] items = ViewNewsHlp.GetNewsItems(state, context.ActualNews);

            HPanel editBlock = null;
            string editHint  = "news_add";

            if (state.BlockHint == editHint)
            {
                if (state.Tag == null)
                {
                    state.Tag = new List <string>();
                }

                string unsaveText = BasketballHlp.AddCommentFromCookie();

                editBlock = new HPanel(
                    Decor.PropertyEdit("newsTitle", "Заголовок новости"),
                    new HPanel(
                        HtmlHlp.CKEditorCreate("newsText", unsaveText, "300px", true)
                        ),
                    ViewTagHlp.GetEditTagsPanel(state, context.Tags.TagBox, state.Tag as List <string>, true),
                    Decor.PropertyEdit("newsOriginName", "Источник"),
                    Decor.PropertyEdit("newsOriginUrl", "Ссылка"),
                    Decor.Button("Добавить новость").MarginTop(10) //.CKEditorOnUpdateAll()
                    .OnClick(string.Format("CK_updateAll(); {0}", BasketballHlp.AddCommentToCookieScript("newsText")))
                    .Event("save_news_add", "addNewsData",
                           delegate(JsonData json)
                {
                    string title      = json.GetText("newsTitle");
                    string text       = json.GetText("newsText");
                    string originName = json.GetText("newsOriginName");
                    string originUrl  = json.GetText("newsOriginUrl");

                    WebOperation operation = state.Operation;

                    if (!operation.Validate(title, "Не задан заголовок"))
                    {
                        return;
                    }

                    if (!operation.Validate(text, "Не задан текст"))
                    {
                        return;
                    }

                    ParentBox editBox = new ParentBox(context.FabricConnection, "1=0");

                    int addNewsId        = editBox.CreateObject(NewsType.News, NewsType.Title.CreateXmlIds(title), DateTime.UtcNow);
                    LightParent editNews = new LightParent(editBox, addNewsId);

                    editNews.Set(NewsType.PublisherId, currentUser.Id);
                    editNews.Set(NewsType.Text, text);
                    editNews.Set(NewsType.OriginName, originName);
                    editNews.Set(NewsType.OriginUrl, originUrl);

                    ViewTagHlp.SaveTags(context, state, editNews);

                    editBox.Update();

                    context.UpdateNews();

                    state.BlockHint = "";
                    state.Tag       = null;

                    BasketballHlp.ResetAddComment();
                }
                           )
                    ).EditContainer("addNewsData").Padding(5, 10).MarginTop(10).Background(Decor.pageBackground);
            }

            IHtmlControl addButton = null;

            if (currentUser != null && !BasketballHlp.NoRedactor(currentUser))
            {
                addButton = Decor.Button("Добавить").MarginLeft(10)
                            .Event("news_add", "", delegate
                {
                    state.Tag = null;
                    state.SetBlockHint(editHint);
                }
                                   );
            }

            return(new HPanel(
                       Decor.Subtitle("Новости"),
                       new HPanel(
                           items.ToArray()
                           ),
                       new HPanel(
                           new HLink("/novosti",
                                     "Все новости",
                                     new HBefore().ContentIcon(5, 12).BackgroundImage(UrlHlp.ImageUrl("pointer.gif")).MarginRight(5).VAlign(-2)
                                     ).FontBold(),
                           addButton
                           ).MarginTop(15),
                       editBlock
                       ));
        }
Exemplo n.º 6
0
        public static IHtmlControl GetRegisterView(SiteState state)
        {
            return(new HPanel(
                       Decor.Title("Регистрация"),
                       Decor.AuthEdit("login", "Логин (*):"),
                       Decor.AuthEdit("yourname", "Ваше имя (*):"),
                       Decor.AuthEdit("email", "E-mail (*):"),
                       Decor.AuthEdit(new HPasswordEdit("password"), "Пароль (*):"),
                       Decor.AuthEdit(new HPasswordEdit("passwordRepeat"), "Введите пароль ещё раз (*):"),
                       new HPanel(
                           Decor.Button("Зарегистрироваться").Event("user_register", "registerData",
                                                                    delegate(JsonData json)
            {
                string login = json.GetText("login");
                string name = json.GetText("yourname");
                string email = json.GetText("email");
                string password = json.GetText("password");
                string passwordRepeat = json.GetText("passwordRepeat");

                WebOperation operation = state.Operation;

                if (!operation.Validate(login, "Не задан логин"))
                {
                    return;
                }
                if (!operation.Validate(email, "Не задана электронная почта"))
                {
                    return;
                }
                if (!operation.Validate(!email.Contains("@"), "Некорректный адрес электронной почты"))
                {
                    return;
                }
                if (!operation.Validate(name, "Не задано имя"))
                {
                    return;
                }
                if (!operation.Validate(password, "Не задан пароль"))
                {
                    return;
                }
                if (!operation.Validate(password != passwordRepeat, "Повтор не совпадает с паролем"))
                {
                    return;
                }

                foreach (LightObject userObj in context.UserStorage.All)
                {
                    if (!operation.Validate(userObj.Get(UserType.Email)?.ToLower() == email?.ToLower(),
                                            "Пользователь с такой электронной почтой уже существует"))
                    {
                        return;
                    }
                }

                ObjectBox box = new ObjectBox(context.UserConnection, "1=0");

                int?createUserId = box.CreateUniqueObject(UserType.User,
                                                          UserType.Login.CreateXmlIds("", login), null);
                if (!operation.Validate(createUserId == null,
                                        "Пользователь с таким логином уже существует"))
                {
                    return;
                }

                LightObject user = new LightObject(box, createUserId.Value);
                FabricHlp.SetCreateTime(user);
                user.Set(UserType.Email, email);
                user.Set(UserType.FirstName, name);
                user.Set(UserType.Password, password);
                user.Set(UserType.NotConfirmed, true);

                box.Update();

                SiteContext.Default.UserStorage.Update();

                Logger.AddMessage("Зарегистрирован пользователь: {0}, {1}, {2}", user.Id, login, email);

                try
                {
                    BasketballHlp.SendRegistrationConfirmation(user.Id, login, email);

                    Logger.AddMessage("Отправлено письмо с подтверждением регистрации.");
                }
                catch (Exception ex)
                {
                    Logger.WriteException(ex);

                    //operation.Validate(true, string.Format("Непредвиденная ошибка при отправке подтверждения: {0}", ex.Message));
                    //return;
                }

                //string xmlLogin = UserType.Login.CreateXmlIds("", login);
                //HttpContext.Current.SetUserAndCookie(xmlLogin);

                //operation.Complete("Вы успешно зарегистрированы!", "");

                state.RedirectUrl = "/confirmation";
            }
                                                                    )
                           )
                       ).EditContainer("registerData"));
        }
Exemplo n.º 7
0
 public SmsService(HttpClient http, SiteState siteState, NavigationManager navigationManager)
 {
     _http              = http;
     _siteState         = siteState;
     _navigationManager = navigationManager;
 }
Exemplo n.º 8
0
 public RoleService(HttpClient http, SiteState siteState, NavigationManager navigationManager) : base(http)
 {
     _siteState         = siteState;
     _navigationManager = navigationManager;
 }
Exemplo n.º 9
0
        public static IHtmlControl GetRestorePasswordView(SiteState state)
        {
            return(new HPanel(
                       Decor.Title("Восстановление пароля"),
                       Decor.AuthEdit("login", "Введите логин:"),
                       Decor.AuthEdit("email", "Или E-mail:"),
                       new HPanel(
                           Decor.Button("Выслать пароль на почту").Event("user_restore", "restoreData",
                                                                         delegate(JsonData json)
            {
                string login = json.GetText("login");
                string email = json.GetText("email");

                WebOperation operation = state.Operation;

                if (!operation.Validate(StringHlp.IsEmpty(login) && StringHlp.IsEmpty(email),
                                        "Введите логин или email"))
                {
                    return;
                }

                LightObject findUser = null;
                if (!StringHlp.IsEmpty(login))
                {
                    string xmlLogin = UserType.Login.CreateXmlIds("", login);
                    findUser = context.UserStorage.FindUser(xmlLogin);
                }
                else
                {
                    foreach (LightObject user in context.UserStorage.All)
                    {
                        if (user.Get(BasketballUserType.Email) == email)
                        {
                            findUser = user;
                            break;
                        }
                    }
                }

                if (!operation.Validate(findUser == null, "Пользователь не найден"))
                {
                    return;
                }

                try
                {
                    HElement answer = h.Div(
                        h.P(string.Format("Ваш логин: {0}", findUser.Get(BasketballUserType.Login))),
                        h.P(string.Format("Ваш пароль: {0}", findUser.Get(BasketballUserType.Password)))
                        );

                    SiteSettings settings = SiteContext.Default.SiteSettings;
                    SmtpClient smtpClient = AuthHlp.CreateSmtpClient(
                        settings.SmtpHost, settings.SmtpPort, settings.SmtpUserName, settings.SmtpPassword);
                    AuthHlp.SendMail(smtpClient, settings.MailFrom, findUser.Get(BasketballUserType.Email),
                                     "Восстановление пароля", answer.ToHtmlText()
                                     );
                }
                catch (Exception ex)
                {
                    Logger.WriteException(ex);

                    operation.Validate(true, string.Format("Непредвиденная ошибка при отправке заявки: {0}", ex.Message));
                    return;
                }

                operation.Message = "Пароль выслан вам на почту";
            }
                                                                         )
                           )
                       ).EditContainer("restoreData"));
        }
Exemplo n.º 10
0
 public SliderService(HttpClient http, SiteState siteState) : base(http)
 {
     _siteState = siteState;
 }
Exemplo n.º 11
0
 /// <summary>
 /// Constructor - should only be used by Dependency Injection
 /// </summary>
 public AliasService(HttpClient http, SiteState siteState) : base(http)
 {
     _siteState = siteState;
 }
Exemplo n.º 12
0
 public SurveyItemService(HttpClient http, SiteState siteState) : base(http)
 {
     _siteState = siteState;
 }
Exemplo n.º 13
0
 public TenantService(HttpClient http, SiteState siteState) : base(http)
 {
     _siteState = siteState;
 }
Exemplo n.º 14
0
        static IHtmlControl GetMessageBlock(IDataLayer forumConnection, SiteState state,
                                            LightObject user, LightObject collocutor, RowLink message, int messageIndex)
        {
            int         messageId = message.Get(CorrespondenceType.Id);
            LightObject author    = message.Get(CorrespondenceType.Inbox) ? collocutor : user;
            DateTime    localTime = message.Get(CorrespondenceType.CreateTime).ToLocalTime();

            IHtmlControl deleteElement = null;

            if (state.BlockHint == "correspondence_moderation")
            {
                deleteElement = new HButton("",
                                            std.BeforeAwesome(@"\f00d", 0)
                                            ).MarginLeft(5).Color(Decor.redColor).Title("удалить комментарий")
                                .Event("delete_message", "", delegate
                {
                    forumConnection.GetScalar("", "Delete From correspondence Where id = @messageId",
                                              new DbParameter("messageId", messageId)
                                              );
                },
                                       messageId
                                       );
            }

            IHtmlControl messageBlock = new HPanel("", new IHtmlControl[] {
                new HPanel(
                    ViewUserHlp.AvatarBlock(author)
                    ).PositionAbsolute().Left(0).Top(0).Padding(7, 5, 10, 5),
                new HPanel(
                    new HPanel(
                        //new HLabel(author.Get(UserType.Login)).FontBold(),
                        new HLink(UrlHlp.ShopUrl("user", author.Id),
                                  author.Get(UserType.FirstName)
                                  ).FontBold(),
                        //new HLabel(author.Get(UserType.FirstName)).MarginLeft(5),
                        new HPanel(
                            new HLabel(localTime.ToString("dd.MM.yyyy HH:mm")).FontSize("90%").Color(Decor.minorColor),
                            deleteElement
                            ).InlineBlock().PositionAbsolute().Right(5)
                        ).PositionRelative().MarginBottom(6),
                    new HTextView(
                        BasketballHlp.PreViewComment(message.Get(CorrespondenceType.Content))
                        ).Block().PaddingBottom(15).BorderBottom("1px solid silver").MarginBottom(5)
                    ).BoxSizing().Width("100%").BorderLeft(Decor.columnBorder).Padding(7, 5, 5, 5)
            }
                                                   ).PositionRelative().PaddingLeft(64).BorderTop("2px solid #fff").Color(Decor.textColor);

            //IHtmlControl messageBlock = new HXPanel(
            //  new HPanel(
            //    new HLink(UrlHlp.ShopUrl("user", author.Id),
            //      author.Get(UserType.Login)
            //    ).FontBold(),
            //    new HLabel(author.Get(UserType.FirstName)).Block()
            //      .MediaTablet(new HStyle().InlineBlock().MarginLeft(5)),
            //    new HPanel(
            //      ViewUserHlp.AvatarBlock(author)
            //    ).MarginTop(5)
            //      .MediaTablet(new HStyle().Display("none"))
            //  ).BoxSizing().WidthLimit("100px", "").Padding(7, 5, 10, 5)
            //    .MediaTablet(new HStyle().Block().PaddingBottom(0).PaddingRight(110)),
            //  new HPanel(
            //    new HPanel(
            //      new HLabel(localTime.ToString("dd.MM.yyyy HH:mm")).MarginRight(5)
            //        .MediaTablet(new HStyle().MarginBottom(5)),
            //      deleteElement
            //    ).Align(false).FontSize("90%").Color(Decor.minorColor),
            //    new HTextView(
            //      BasketballHlp.PreViewComment(message.Get(CorrespondenceType.Content))
            //    ).PaddingBottom(15).MarginBottom(5).BorderBottom("1px solid silver")
            //  ).BoxSizing().Width("100%").BorderLeft(Decor.columnBorder).Padding(7, 5, 5, 5)
            //    .MediaTablet(new HStyle().Block().MarginTop(-19))
            //).BorderTop("2px solid #fff");

            if (messageIndex % 2 != 0)
            {
                messageBlock.Background(Decor.evenBackground);
            }

            return(messageBlock);
        }
Exemplo n.º 15
0
        public static IHtmlControl GetAddPanel(BasketballContext context, SiteState state,
                                               LightObject user, LightObject collocutor, bool sendFromUserView)
        {
            if (user == null)
            {
                return(null);
            }

            if (user.Id == collocutor.Id)
            {
                return(null);
            }

            IHtmlControl editPanel = null;

            if (state.BlockHint == "messageAdd")
            {
                string commentValue = BasketballHlp.AddCommentFromCookie();

                editPanel = new HPanel(
                    new HTextArea("messageContent", commentValue).BoxSizing().Width("100%")
                    .Height("10em").MarginTop(5).MarginBottom(5),
                    Decor.Button("отправить")
                    .OnClick(BasketballHlp.AddCommentToCookieScript("messageContent"))
                    .Event("message_add_save", "messageData",
                           delegate(JsonData json)
                {
                    string content = json.GetText("messageContent");
                    if (StringHlp.IsEmpty(content))
                    {
                        return;
                    }

                    DialogueHlp.SendMessage(context, user.Id, collocutor.Id, content);

                    state.BlockHint = "";

                    BasketballHlp.ResetAddComment();

                    if (sendFromUserView)
                    {
                        state.Operation.Message = "Сообщение успешно отправлено";
                    }
                }
                           ),
                    new HElementControl(
                        h.Script(h.type("text/javascript"), "$('.messageContent').focus();"),
                        ""
                        )
                    ).EditContainer("messageData");
            }

            HButton moderatorButton = null;
            HPanel  moderatorPanel  = null;

            if (!sendFromUserView)
            {
                moderatorButton = new HButton("",
                                              std.BeforeAwesome(@"\f1e2", 0)
                                              ).PositionAbsolute().Right(5).Top(0)
                                  .Title("Модерирование личных сообщений").FontSize(14)
                                  .Color(state.BlockHint == correspondenceModeration ? Decor.redColor : Decor.disabledColor)
                                  .Event("correspondence_moderation_set", "", delegate
                {
                    state.SetBlockHint(correspondenceModeration);
                });

                if (state.BlockHint == correspondenceModeration)
                {
                    bool lockedCollocutor = user.Get(BasketballUserType.LockedUserIds, collocutor.Id);
                    moderatorPanel = new HPanel(
                        Decor.ButtonMidi(!lockedCollocutor ? "Заблокировать собеседника" : "Разблокировать собеседника")
                        .Event("collocutor_locked", "", delegate
                    {
                        LightObject editUser = DataBox.LoadObject(context.UserConnection, UserType.User, user.Id);
                        editUser.Set(BasketballUserType.LockedUserIds, collocutor.Id, !lockedCollocutor);
                        editUser.Box.Update();
                        context.UserStorage.Update();
                    }),
                        new HSpoiler(Decor.ButtonMidi("Удаление переписки").Block().FontBold(false),
                                     new HPanel(
                                         Decor.ButtonMidi("Удалить? (без подтверждения)")
                                         .MarginTop(5).MarginLeft(10)
                                         .Event("correspondence_delete", "", delegate
                    {
                        context.ForumConnection.GetScalar("",
                                                          "Delete From correspondence Where user_id = @userId and collocutor_id = @collocutorId",
                                                          new DbParameter("userId", user.Id), new DbParameter("collocutorId", collocutor.Id)
                                                          );

                        context.ForumConnection.GetScalar("",
                                                          "Delete From dialogue Where user_id = @userId and collocutor_id = @collocutorId",
                                                          new DbParameter("userId", user.Id), new DbParameter("collocutorId", collocutor.Id)
                                                          );

                        context.UpdateUnreadDialogs();
                    })
                                         )
                                     ).MarginTop(10)
                        ).MarginTop(10);
                }
            }

            bool locked = user.Get(BasketballUserType.LockedUserIds, collocutor.Id) ||
                          collocutor.Get(BasketballUserType.LockedUserIds, user.Id);

            return(new HPanel(
                       new HPanel(
                           Decor.ButtonMidi("Написать сообщение")
                           .Hide(locked)
                           .Event("message_add", "", delegate
            {
                state.SetBlockHint("messageAdd");
            }
                                  ),
                           new HLabel("Вы не можете отправить сообщение этому пользователю").Hide(!locked)
                           .MarginLeft(10).Color(Decor.subtitleColor),
                           moderatorButton
                           ).PositionRelative(),
                       editPanel,
                       moderatorPanel
                       ).MarginTop(10).MarginBottom(10));
        }
Exemplo n.º 16
0
        public static IHtmlControl GetCorrespondenceView(SiteState state,
                                                         IDataLayer forumConnection, LightObject user, LightObject collocutor, out string title)
        {
            title = "Личные сообщения";

            int pageIndex    = state.Option.Get(OptionType.CorrespondencePageIndex);
            int messageCount = DatabaseHlp.RowCount(forumConnection, "", "correspondence",
                                                    "user_id = @userId and collocutor_id = @collocutorId",
                                                    new DbParameter("userId", user.Id), new DbParameter("collocutorId", collocutor.Id)
                                                    );
            int pageCount = BinaryHlp.RoundUp(messageCount, 5);

            HButton prevButton = null;

            if (pageCount - 1 > pageIndex)
            {
                prevButton = Decor.ButtonMidi("предыдущие").Event("page_prev", "",
                                                                  delegate
                {
                    state.Option.Set(OptionType.CorrespondencePageIndex, pageIndex + 1);
                }
                                                                  );
            }

            HButton nextButton = null;

            if (pageIndex > 0)
            {
                nextButton = Decor.ButtonMidi("следующие").Event("page_next", "",
                                                                 delegate
                {
                    state.Option.Set(OptionType.CorrespondencePageIndex, pageIndex - 1);
                }
                                                                 );
            }

            TableLink messageLink = DialogueHlp.LoadCorrespondenceLink(forumConnection,
                                                                       string.Format("user_id = @userId and collocutor_id = @collocutorId order by create_time desc limit 5 offset {0}",
                                                                                     pageIndex * 5
                                                                                     ),
                                                                       new DbParameter("userId", user.Id), new DbParameter("collocutorId", collocutor.Id)
                                                                       );

            RowLink[]           messages      = messageLink.AllRows;
            List <IHtmlControl> messageBlocks = new List <IHtmlControl>();

            if (prevButton != null || nextButton != null)
            {
                messageBlocks.Add(
                    new HPanel(
                        new HPanel(prevButton), new HPanel(nextButton)
                        ).MarginTop(5).MarginBottom(5)
                    );
            }

            for (int i = messages.Length - 1; i >= 0; --i)
            {
                //if (i == 2)
                //  messageBlocks.Add(new HAnchor("bottom"));

                messageBlocks.Add(GetMessageBlock(forumConnection, state, user, collocutor, messages[i], i));
            }

            IHtmlControl addPanel = GetAddPanel(context, state, user, collocutor, false);

            return(new HPanel(
                       GetCorrespondenceHeader(state, user, collocutor),
                       new HPanel(
                           messageBlocks.ToArray()
                           ).BorderBottom(Decor.bottomBorder),
                       addPanel
                       ));
        }
Exemplo n.º 17
0
 public UrlMappingService(HttpClient http, SiteState siteState) : base(http)
 {
     _siteState = siteState;
 }
Exemplo n.º 18
0
 public HtmlTextService(HttpClient http, SiteState siteState) : base(http)
 {
     _siteState = siteState;
 }
Exemplo n.º 19
0
 public HtmlTextService(HttpClient http, SiteState sitestate)
 {
     this.http      = http;
     this.sitestate = sitestate;
 }
Exemplo n.º 20
0
        static IHtmlControl GetNewsEditPanel(SiteState state, TopicStorage topic)
        {
            LightObject news = topic.Topic;

            string blockHint = string.Format("news_edit_{0}", news.Id);

            IHtmlControl redoPanel = null;

            if (state.BlockHint == blockHint)
            {
                IHtmlControl deletePanel = null;
                if (state.ModeratorMode)
                {
                    deletePanel = DeleteTopicPanel(state, topic);
                }

                if (state.Tag == null)
                {
                    state.Tag = ViewTagHlp.GetTopicDisplayTags(context.Tags.TagBox, topic.Topic);
                }

                redoPanel = new HPanel(
                    deletePanel,
                    Decor.PropertyEdit("newsTitle", "Заголовок новости", news.Get(NewsType.Title)),
                    new HPanel(
                        HtmlHlp.CKEditorCreate("newsText", news.Get(NewsType.Text), "300px", true)
                        ),
                    ViewTagHlp.GetEditTagsPanel(state, context.Tags.TagBox, state.Tag as List <string>, false),
                    Decor.PropertyEdit("newsOriginName", "Источник", news.Get(NewsType.OriginName)),
                    Decor.PropertyEdit("newsOriginUrl", "Ссылка", news.Get(NewsType.OriginUrl)),
                    Decor.Button("Изменить новость").CKEditorOnUpdateAll().MarginTop(10)
                    .Event("save_news_edit", "editNewsData",
                           delegate(JsonData json)
                {
                    string title      = json.GetText("newsTitle");
                    string text       = json.GetText("newsText");
                    string originName = json.GetText("newsOriginName");
                    string originUrl  = json.GetText("newsOriginUrl");

                    WebOperation operation = state.Operation;

                    if (!operation.Validate(title, "Не задан заголовок"))
                    {
                        return;
                    }
                    if (!operation.Validate(text, "Не задан текст"))
                    {
                        return;
                    }

                    LightKin editNews = DataBox.LoadKin(context.FabricConnection, NewsType.News, news.Id);

                    editNews.SetWithoutCheck(NewsType.Title, title);

                    editNews.Set(NewsType.Text, text);
                    editNews.Set(NewsType.OriginName, originName);
                    editNews.Set(NewsType.OriginUrl, originUrl);

                    editNews.Set(ObjectType.ActTill, DateTime.UtcNow);

                    ViewTagHlp.SaveTags(context, state, editNews);

                    editNews.Box.Update();

                    context.UpdateNews();
                    context.NewsStorages.ForTopic(news.Id).UpdateTopic();

                    state.BlockHint = "";
                },
                           news.Id
                           )
                    ).EditContainer("editNewsData")
                            .Padding(5, 10).MarginTop(10).Background(Decor.pageBackground);
            }

            return(new HPanel(
                       Decor.Button("Редактировать")
                       .Event("news_edit", "", delegate
            {
                state.SetBlockHint(blockHint);
            }
                              ),
                       redoPanel
                       ).MarginTop(10));
        }
Exemplo n.º 21
0
 public SiteService(HttpClient http, SiteState sitestate, IUriHelper urihelper)
 {
     this.http      = http;
     this.sitestate = sitestate;
     this.urihelper = urihelper;
 }
 public ModuleDefinitionService(HttpClient http, SiteState siteState, NavigationManager navigationManager) : base(http)
 {
     _http              = http;
     _siteState         = siteState;
     _navigationManager = navigationManager;
 }
Exemplo n.º 23
0
 partial void OnStateChanging(SiteState value);
Exemplo n.º 24
0
 public PackageService(HttpClient http, SiteState siteState) : base(http)
 {
     _siteState = siteState;
 }
Exemplo n.º 25
0
 public ModuleDefinitionService(HttpClient http, SiteState siteState) : base(http)
 {
     _http      = http;
     _siteState = siteState;
 }
Exemplo n.º 26
0
 public ModuleService(HttpClient http, SiteState sitestate, NavigationManager NavigationManager) : base(http, sitestate, NavigationManager)
 {
     this.http              = http;
     this.sitestate         = sitestate;
     this.NavigationManager = NavigationManager;
 }
Exemplo n.º 27
0
        public static IHtmlControl GetCenter(HttpContext httpContext, SiteState state,
                                             LightObject currentUser, string kind, int?id,
                                             out string title, out string description, out SchemaOrg schema, out bool wideContent)
        {
            title       = "";
            description = "";
            schema      = null;
            wideContent = false;

            SiteSettings settings = context.SiteSettings;

            switch (kind)
            {
            case "":
            {
                title       = store.SEO.Get(SEOType.MainTitle);
                description = store.SEO.Get(SEOType.MainDescription);
                LightSection main = store.Sections.FindMenu("main");
                return(ViewHlp.GetMainView(state, currentUser));
            }

            case "news":
            {
                if (!context.News.ObjectById.Exist(id))
                {
                    return(null);
                }
                TopicStorage topicStorage = context.NewsStorages.ForTopic(id ?? 0);
                LightKin     topic        = topicStorage.Topic;
                //string tagsDisplay;
                IHtmlControl view = ViewNewsHlp.GetNewsView(state, currentUser, topicStorage, out description);

                title = topic.Get(NewsType.Title);

                //string postfix = "";
                //if (!StringHlp.IsEmpty(tagsDisplay))
                //  postfix = ". ";
                //description = string.Format("{0}{1}Живое обсуждение баскетбольных событий на basketball.ru.com",
                //  tagsDisplay, postfix
                //);

                string logoUrl = settings.FullUrl("/images/logo.gif");
                schema = new SchemaOrg("NewsArticle", settings.FullUrl(UrlHlp.ShopUrl("news", id)),
                                       title, new string[] { logoUrl }, topic.Get(ObjectType.ActFrom), topic.Get(ObjectType.ActTill),
                                       topic.Get(TopicType.OriginName), settings.Organization,
                                       logoUrl, description
                                       );

                return(view);
            }

            case "article":
            {
                if (!context.Articles.ObjectById.Exist(id))
                {
                    return(null);
                }
                TopicStorage topicStorage = context.ArticleStorages.ForTopic(id ?? 0);
                LightKin     topic        = topicStorage.Topic;
                title       = topic.Get(ArticleType.Title);
                description = topic.Get(ArticleType.Annotation);

                string logoUrl = settings.FullUrl("/images/logo.gif");
                schema = new SchemaOrg("Article", settings.FullUrl(UrlHlp.ShopUrl("article", id)),
                                       title, new string[] { logoUrl }, topic.Get(ObjectType.ActFrom), topic.Get(ObjectType.ActTill),
                                       topic.Get(TopicType.OriginName), settings.Organization,
                                       logoUrl, description
                                       );
                wideContent = topic.Get(ArticleType.WideContent);
                return(ViewArticleHlp.GetArticleView(state, currentUser, topicStorage));
            }

            case "topic":
            {
                TopicStorage topic = context.Forum.TopicsStorages.ForTopic(id ?? 0);
                title = topic.Topic.Get(TopicType.Title);

                int pageNumber = 0;
                {
                    string pageArg      = httpContext.Get("page");
                    int    messageCount = topic.MessageLink.AllRows.Length;
                    if (pageArg == "last" && messageCount > 0)
                    {
                        pageNumber = BinaryHlp.RoundUp(messageCount, ViewForumHlp.forumMessageCountOnPage) - 1;
                    }
                    else
                    {
                        pageNumber = ConvertHlp.ToInt(pageArg) ?? 0;
                    }
                }

                return(ViewForumHlp.GetTopicView(state, currentUser, topic, pageNumber));
            }

            case "tags":
            {
                int?tagId      = httpContext.GetUInt("tag");
                int pageNumber = httpContext.GetUInt("page") ?? 0;
                return(ViewNewsHlp.GetTagView(state, currentUser, tagId, pageNumber, out title, out description));
            }

            case "search":
            {
                return(ViewNewsHlp.GetFoundTagListView(state, out title));
            }

            case "user":
            {
                LightObject user = context.UserStorage.FindUser(id ?? -1);
                if (user == null)
                {
                    return(null);
                }
                title = string.Format("{0} - Basketball.ru.com", user.Get(UserType.Login));
                return(ViewUserHlp.GetUserView(state, currentUser, user));
            }

            case "page":
            {
                LightSection section = store.Sections.FindSection(id);
                title       = FabricHlp.GetSeoTitle(section, section.Get(SectionType.Title));
                description = FabricHlp.GetSeoDescription(section, section.Get(SectionType.Annotation));

                int    pageNumber = httpContext.GetUInt("page") ?? 0;
                string designKind = section.Get(SectionType.DesignKind);
                switch (designKind)
                {
                case "news":
                {
                    int[] allNewsIds = context.News.AllObjectIds;
                    return(ViewNewsHlp.GetNewsListView(state, currentUser, pageNumber));
                }

                case "articles":
                    return(ViewArticleHlp.GetArticleListView(state, currentUser, pageNumber));

                case "forum":
                    return(ViewForumHlp.GetForumView(state, currentUser, section));

                case "forumSection":
                    return(ViewForumHlp.GetForumSectionView(state, currentUser, section));

                default:
                    return(null);
                }
            }

            case "dialog":
            {
                if (currentUser == null)
                {
                    return(null);
                }

                if (id == null)
                {
                    return(ViewDialogueHlp.GetDialogueView(state,
                                                           context.ForumConnection, context.UserStorage, currentUser, out title
                                                           ));
                }

                LightObject collocutor = context.UserStorage.FindUser(id.Value);
                if (collocutor == null)
                {
                    return(null);
                }

                return(ViewDialogueHlp.GetCorrespondenceView(state, context.ForumConnection,
                                                             currentUser, collocutor, out title
                                                             ));
            }

            case "passwordreset":
                title = "Восстановление пароля - basketball.ru.com";
                return(ViewHlp.GetRestorePasswordView(state));

            case "register":
                title = "Регистрация - basketball.ru.com";
                return(ViewHlp.GetRegisterView(state));

            case "confirmation":
            {
                title = "Подтверждение аккаунта";

                int?   userId = httpContext.GetUInt("id");
                string hash   = httpContext.Get("hash");

                if (userId == null)
                {
                    return(ViewUserHlp.GetMessageView(
                               "Вам выслано письмо с кодом активации. Чтобы завершить процедуру регистрации, пройдите по ссылке, указанной в письме, и учётная запись будет активирована. Если вы не получили письмо, то попробуйте войти на сайт со своим логином и паролем. Тогда письмо будет отправлено повторно."
                               ));
                }

                if (StringHlp.IsEmpty(hash))
                {
                    return(null);
                }

                LightObject user = context.UserStorage.FindUser(userId.Value);
                if (userId == null)
                {
                    return(null);
                }

                if (!user.Get(UserType.NotConfirmed))
                {
                    return(ViewUserHlp.GetMessageView("Пользователь успешно активирован"));
                }

                string login  = user.Get(UserType.Login);
                string etalon = UserHlp.CalcConfirmationCode(user.Id, login, "bbbin");
                if (hash?.ToLower() != etalon?.ToLower())
                {
                    return(ViewUserHlp.GetMessageView("Неверный хэш"));
                }

                LightObject editUser = DataBox.LoadObject(context.UserConnection, UserType.User, user.Id);
                editUser.Set(UserType.NotConfirmed, false);
                editUser.Box.Update();

                context.UserStorage.Update();

                string xmlLogin = UserType.Login.CreateXmlIds("", login);
                HttpContext.Current.SetUserAndCookie(xmlLogin);

                state.RedirectUrl = "/";

                return(new HPanel());
            }
            }

            return(null);
        }
Exemplo n.º 28
0
        public TenantResolver(IHttpContextAccessor accessor, IAliasRepository aliasRepository, ITenantRepository tenantRepository, SiteState siteState)
        {
            int    aliasId   = -1;
            string aliasName = "";

            // get alias identifier based on request context
            if (accessor.HttpContext != null)
            {
                // check if an alias is passed as a querystring parameter ( for cross tenant access )
                if (accessor.HttpContext.Request.Query.ContainsKey("aliasid"))
                {
                    aliasId = int.Parse(accessor.HttpContext.Request.Query["aliasid"]);
                }
                else // get the alias from the request url
                {
                    aliasName = accessor.HttpContext.Request.Host.Value;
                    string   path     = accessor.HttpContext.Request.Path.Value;
                    string[] segments = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                    if (segments.Length > 1 && segments[1] == "api" && segments[0] != "~")
                    {
                        aliasName += "/" + segments[0];
                    }

                    if (aliasName.EndsWith("/"))
                    {
                        aliasName = aliasName.Substring(0, aliasName.Length - 1);
                    }
                }
            }
            else // background processes can pass in an alias using the SiteState service
            {
                aliasId = siteState?.Alias?.AliasId ?? -1;
            }

            // get the alias and tenant
            IEnumerable <Alias> aliases = aliasRepository.GetAliases().ToList(); // cached

            if (aliasId != -1)
            {
                _alias = aliases.FirstOrDefault(item => item.AliasId == aliasId);
            }
            else
            {
                _alias = aliases.FirstOrDefault(item => item.Name == aliasName
                                                //if here is only one alias and other methods fail, take it (case of startup install)
                                                || aliases.Count() == 1);
            }

            if (_alias != null)
            {
                IEnumerable <Tenant> tenants = tenantRepository.GetTenants(); // cached
                _tenant = tenants.FirstOrDefault(item => item.TenantId == _alias.TenantId);
            }
        }
Exemplo n.º 29
0
 public ThemeService(HttpClient http, SiteState sitestate, NavigationManager NavigationManager)
 {
     this.http              = http;
     this.sitestate         = sitestate;
     this.NavigationManager = NavigationManager;
 }
Exemplo n.º 30
0
        public static void SaveTags(BasketballContext context, SiteState state, LightParent editTopic)
        {
            List <string> tags = state.Tag as List <string>;

            if (tags == null)
            {
                return;
            }

            ObjectHeadBox editBox = null;
            List <int>    tagIds  = new List <int>();

            foreach (string tag in tags)
            {
                if (StringHlp.IsEmpty(tag))
                {
                    continue;
                }

                string tagKey = tag.ToLower();
                {
                    int tagId;
                    if (context.Tags.TagIdByKey.TryGetValue(tagKey, out tagId))
                    {
                        tagIds.Add(tagId);
                        continue;
                    }
                }

                string xmlIds = TagType.DisplayName.CreateXmlIds(tag);
                //RowLink tagRow = context.Tags.ObjectByXmlIds.AnyRow(xmlIds);
                //if (tagRow != null)
                //{
                //  tagIds.Add(tagRow.Get(ObjectType.ObjectId));
                //  continue;
                //}

                if (editBox == null)
                {
                    editBox = new ObjectHeadBox(context.FabricConnection, "1=0");
                }

                int?newTagId = editBox.CreateUniqueObject(TagType.Tag, xmlIds, null);
                if (newTagId == null)
                {
                    continue;
                }

                tagIds.Add(newTagId.Value);
            }

            if (editBox != null)
            {
                editBox.Update();
                context.UpdateTags();
            }

            for (int i = 0; i < tagIds.Count; ++i)
            {
                int tagId = tagIds[i];
                if (tagId != editTopic.GetChildId(TopicType.TagLinks, i))
                {
                    editTopic.SetChildId(TopicType.TagLinks, i, tagId);
                }
            }

            RowLink[] allTagRows = editTopic.AllChildRows(TopicType.TagLinks);
            for (int i = allTagRows.Length - 1; i >= tagIds.Count; --i)
            {
                editTopic.RemoveChildLink(TopicType.TagLinks, i);
            }
        }
Exemplo n.º 31
0
		/// <summary>
		/// Converts site state to server state.
		/// </summary>
		/// <param name="siteState">Site state to convert.</param>
		/// <returns>Server state.</returns>
		private static ServerState ConvertSiteStateToServerState(SiteState siteState)
		{
			switch(siteState)
			{
				case SiteState.Started:
					return ServerState.Started;
				case SiteState.Starting:
					return ServerState.Starting;
				case SiteState.Stopped:
					return ServerState.Stopped;
				case SiteState.Stopping:
					return ServerState.Stopping;
				default:
					return ServerState.Unknown;
			}
		}
Exemplo n.º 32
0
        public static IHtmlControl GetEditTagsPanel(SiteState state,
                                                    ObjectHeadBox tagBox, List <string> tags, bool isAdd)
        {
            if (tags == null)
            {
                return(null);
            }

            List <IHtmlControl> tagElements = new List <IHtmlControl>();
            int i = -1;

            foreach (string tag in tags)
            {
                ++i;
                int index = i;
                tagElements.Add(
                    new HPanel(
                        new HLabel(tag),
                        new HButton("",
                                    std.BeforeAwesome(@"\f00d", 0)
                                    ).MarginLeft(5).Color(Decor.redColor).Title("удалить тег")
                        .Event("tag_remove", "", delegate
                {
                    if (index < tags.Count)
                    {
                        tags.RemoveAt(index);
                    }
                },
                               index
                               )
                        ).InlineBlock().MarginTop(5).MarginRight(5)
                    );
            }

            string addTagName = string.Format("addTag_{0}", state.OperationCounter);
            string onClick    = !isAdd ? ";" :
                                string.Format("CK_updateAll(); {0}", BasketballHlp.AddCommentToCookieScript("newsText"));

            return(new HPanel(
                       new HPanel(
                           tagElements.ToArray()
                           ).MarginBottom(5),
                       new HPanel(
                           new HTextEdit(addTagName).Width(400).MarginRight(5).MarginBottom(5)
                           .MediaSmartfon(new HStyle().Width("100%")),
                           Decor.Button("Добавить тэг").VAlign(-1).MarginBottom(5)
                           .OnClick(onClick)
                           .Event("tag_add", "addTagData",
                                  delegate(JsonData json)
            {
                string addTag = json.GetText(addTagName);
                if (StringHlp.IsEmpty(addTag))
                {
                    return;
                }

                if (tags.Contains(addTag))
                {
                    return;
                }

                string[] newTags = addTag.Split(',');
                foreach (string rawTag in newTags)
                {
                    string tag = rawTag.Trim();
                    if (!StringHlp.IsEmpty(tag))
                    {
                        tags.Add(tag);
                    }
                }

                state.OperationCounter++;
            })
                           ).EditContainer("addTagData")
                       ).MarginTop(5));
        }
Exemplo n.º 33
0
 public ModuleService(HttpClient http, SiteState sitestate)
 {
     this.http      = http;
     this.sitestate = sitestate;
 }
Exemplo n.º 34
0
 public SiteDescriptor(string name, SiteState state)
 {
     Name  = name;
     State = state;
 }
Exemplo n.º 35
0
        public ActionResult Tagged(string id)
        {
            try
            {
                SiteState state = new SiteState(Url);
                StackyRepository repository = new StackyRepository(state);

                return View("Questions", new QuestionsModel(repository.GetQuestions(tags: new string[] { id }, includeBody: true, page: state.Page, pageSize: state.PageSize), state));
            }
            catch (ApiException ex)
            {
                return View("Error", new HandleErrorInfo(ex, "Question", "Active"));
            }
        }
 partial void OnStateChanging(SiteState value);