private MenuItem GetProfileMenuItem()
 {
     return(new MenuItem("Profile")
     {
         MenuUrlInfo = UrlFactory.Create <AccountController>(m => m.UserProfile())
     });
 }
        public IHttpActionResult CreateTestScript(TestScript model)
        {
            model.CreatedByUserId = base.UserId;
            if (model.StoryId <= 0)
            {
                ModelState.AddModelError("Story", "StoryId is required");
            }
            if (ModelState.IsValid)
            {
                var newScriptId = _repoFactory.TestScripts.CreateTestScript(model);
                if (newScriptId.HasValue)
                {
                    CreateTestScriptAssigneeMapping(newScriptId.Value, model.AssignedToDeveloperId, model.AssignedToDevManagerId, model.AssignedToBusinessAnalystId,
                                                    model.AssignedToBusinessStakeholderId, model.TestScriptStatus);

                    model.TestScriptId = newScriptId.Value;

                    if (!string.IsNullOrWhiteSpace(model.AssignedToDeveloperId) &&
                        !string.Equals(model.AssignedToDeveloperId, UserId, System.StringComparison.OrdinalIgnoreCase))
                    {
                        var receipientName = _cacheService.GetUserName(model.AssignedToDeveloperId);
                        if (!string.IsNullOrWhiteSpace(receipientName))
                        {
                            var receipient     = new MailUser(model.AssignedToDeveloperId, receipientName);
                            var actor          = new MailUser(UserId, DisplayName);
                            var testScriptLink = UrlFactory.GetTestScriptPageUrl(model.StoryId, model.TestScriptId);
                            _emailService.SendMail(receipient, Core.Enumerations.EmailType.TestScriptAssigned, actor, testScriptLink);
                        }
                    }

                    return(Created($"/api/test-scripts/{model.TestScriptId}", model));
                }
            }
            return(BadRequest(ModelState));
        }
Example #3
0
        public void TestGenerateUrlFactory(DataType d, string urlSuffix)
        {
            string defaultPath = "https://photobookwebapi1.azurewebsites.net/api/";
            string testUrl     = UrlFactory.Generate(d);

            Assert.That(testUrl, Is.EqualTo(defaultPath + urlSuffix));
        }
 private MenuItem GetHomeMenuItem()
 {
     return(new MenuItem("Home")
     {
         MenuUrlInfo = UrlFactory.Create <HomeController>(m => m.Index())
     });
 }
Example #5
0
 protected void Page_Init(object sender, EventArgs e)
 {
     this.Title      = this.HostProfile.SiteTitle + " - " + this.HostProfile.TagLine + ".";
     this.Caption    = "Upcoming stories";
     this.PageName   = UrlFactory.PageName.NewStories;
     this.RssFeedUrl = UrlFactory.CreateUrl(UrlFactory.PageName.NewStoriesRss);
 }
Example #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //TODO: GJ: decode url

            string url   = Request["url"].Trim();
            string title = Request["title"];

            if (String.IsNullOrEmpty(title))
            {
                title = "";
            }

            title = title.Trim();

            //TODO: GJ: we could improve performance here (better story cache)
            Incremental.Kick.Dal.Story story = Incremental.Kick.Dal.Story.FetchStoryByUrl(url);

            if (story == null)
            {
                this.Response.Redirect("~/submit/?url=" + HttpUtility.UrlEncode(url) + "&title=" + HttpUtility.UrlEncode(title));
            }
            else
            {
                //TODO: GJ: should we auto kick???
                this.Response.Redirect(UrlFactory.CreateUrl(UrlFactory.PageName.ViewStory, story.StoryIdentifier, CategoryCache.GetCategory(story.CategoryID, this.HostProfile.HostID).CategoryIdentifier));
            }
        }
Example #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Paging.PageNumber = UrlParameters.PageNumber;
            this.Paging.PageSize   = UrlParameters.PageSize;

            if (!this.UrlParameters.CategoryIdentifierSpecified)
            {
                this.StoryList.DataBind(StoryCache.GetPopularStories(this.HostProfile.HostID, false, this.UrlParameters.StoryListSortBy, this.UrlParameters.PageNumber, this.UrlParameters.PageSize));
                this.Paging.RecordCount = StoryCache.GetPopularStoriesCount(this.HostProfile.HostID, false, this.UrlParameters.StoryListSortBy);
                this.Paging.BaseUrl     = UrlFactory.CreateUrl(UrlFactory.PageName.Home) + "/upcoming/popular/" + this.UrlParameters.StoryListSortBy.ToString().ToLower();
            }
            else
            {
                this.StoryList.DataBind(StoryCache.GetCategoryStories(this.UrlParameters.CategoryID, false, this.HostProfile.HostID, this.UrlParameters.PageNumber, this.UrlParameters.PageSize));
                this.Paging.RecordCount = StoryCache.GetCategoryStoryCount(this.UrlParameters.CategoryID, false, this.HostProfile.HostID);
                this.Paging.BaseUrl     = UrlFactory.CreateUrl(UrlFactory.PageName.ViewCategoryNewStories, this.UrlParameters.CategoryIdentifier);
            }

            switch (this.UrlParameters.StoryListSortBy)
            {
            case StoryListSortBy.Today:
                this.PageName = UrlFactory.PageName.UpcomingToday;
                break;

            case StoryListSortBy.PastWeek:
                this.PageName = UrlFactory.PageName.UpcomingWeek;
                break;

            default:
                this.PageName = UrlFactory.PageName.NewStories;
                break;
            }
        }
        public async Task <Response> CreateUrl(UrlModel model)
        {
            if (!await IsShortUrlPathTaken(model.ShortUrlPath))
            {
                return(ResponseFactory.InitializeResponseFailed($"ShortUrlPath {model.ShortUrlPath} already taken", model));
            }

            var path = string.IsNullOrWhiteSpace(model.ShortUrlPath)
                ? Utilities.GenerateRandomPath(
                Convert.ToInt32(_configuration["Path:Length"]),
                _configuration["Path:Characters"]
                )
                : model.ShortUrlPath;

            var hashedIpAddress = Utilities.HashIpAddress(
                "",
                _configuration["Hashing:Pepper"],
                Convert.ToInt32(_configuration["Hashing:Iterations"])
                );

            var newUrl = UrlFactory.InitializeUrl(
                model.OriginalUrl,
                path,
                hashedIpAddress
                );

            await _repository.CreateUrl(newUrl);

            return(ResponseFactory.InitializeResponseSuccess($"New Short Url {newUrl.ShortUrlPath}", newUrl));
        }
        public Actor GetUser(TwitterUser twitterUser)
        {
            var actorUrl = UrlFactory.GetActorUrl(_instanceSettings.Domain, twitterUser.Acct);
            var acct     = twitterUser.Acct.ToLowerInvariant();

            // Extract links, mentions, etc
            var description = twitterUser.Description;

            if (!string.IsNullOrWhiteSpace(description))
            {
                var extracted = _statusExtractor.Extract(description, _instanceSettings.ResolveMentionsInProfiles);
                description = extracted.content;

                _statisticsHandler.ExtractedDescription(extracted.tags.Count(x => x.type == "Mention"));
            }

            var user = new Actor
            {
                id                        = actorUrl,
                type                      = "Service",
                followers                 = $"{actorUrl}/followers",
                preferredUsername         = acct,
                name                      = twitterUser.Name,
                inbox                     = $"{actorUrl}/inbox",
                summary                   = description,
                url                       = actorUrl,
                manuallyApprovesFollowers = twitterUser.Protected,
                publicKey                 = new PublicKey()
                {
                    id           = $"{actorUrl}#main-key",
                    owner        = actorUrl,
                    publicKeyPem = _cryptoService.GetUserPem(acct)
                },
                icon = new Image
                {
                    mediaType = "image/jpeg",
                    url       = twitterUser.ProfileImageUrl
                },
                image = new Image
                {
                    mediaType = "image/jpeg",
                    url       = twitterUser.ProfileBannerURL
                },
                attachment = new []
                {
                    new UserAttachment
                    {
                        type  = "PropertyValue",
                        name  = "Official",
                        value = $"<a href=\"https://twitter.com/{acct}\" rel=\"me nofollow noopener noreferrer\" target=\"_blank\"><span class=\"invisible\">https://</span><span class=\"ellipsis\">twitter.com/{acct}</span></a>"
                    }
                },
                endpoints = new EndPoints
                {
                    sharedInbox = $"https://{_instanceSettings.Domain}/inbox"
                }
            };

            return(user);
        }
        public IDictionary <string, string> GetClientParameters(HttpContext context, string clientId)
        {
            var client       = Options.Value.Clients[clientId];
            var authority    = context.GetIdentityServerIssuerUri();
            var responseType = "";

            if (!client.Properties.TryGetValue(ApplicationProfilesPropertyNames.Profile, out var type))
            {
                throw new InvalidOperationException($"Can't determine the type for the client '{clientId}'");
            }

            switch (type)
            {
            case ApplicationProfiles.IdentityServerSPA:
            case ApplicationProfiles.SPA:
            case ApplicationProfiles.NativeApp:
                responseType = "code";
                break;

            default:
                throw new InvalidOperationException($"Invalid application type '{type}' for '{clientId}'.");
            }

            return(new Dictionary <string, string>
            {
                ["authority"] = authority,
                ["client_id"] = client.ClientId,
                ["redirect_uri"] = UrlFactory.GetAbsoluteUrl(context, client.RedirectUris.First()),
                ["post_logout_redirect_uri"] = UrlFactory.GetAbsoluteUrl(context, client.PostLogoutRedirectUris.First()),
                ["response_type"] = responseType,
                ["scope"] = string.Join(" ", client.AllowedScopes)
            });
        }
Example #11
0
        public void generateLinkForRelatedResource_UT()
        {
            string expectEdUrl = @"/api/item/4";
            string testURL     = "";

            Item testItem = new Item();

            testItem.ItemId = 4;
            testItem.Name   = "Test item";

            OrderLine testOrderLine = new OrderLine();

            testOrderLine.OrderLineId = 182;
            testOrderLine.OrderItem   = testItem;

            Link testLink = new Link();

            //Get a property that has a related resource attribute.
            PropertyInfo p = testOrderLine.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(RelatedResource))).ToList <PropertyInfo>().FirstOrDefault();

            UrlFactory urlGenerator = new UrlFactory(@"/api");

            testURL         = urlGenerator.generateUrl(p.GetValue(testOrderLine, null));
            testLink.Url    = testURL;
            testLink.Method = HTTPMethods.GET;

            testLink.Relation = p.GetCustomAttribute <RelatedResource>().relationship;

            Assert.IsTrue(expectEdUrl.CompareTo(testLink.Url) == 0);
            Assert.IsTrue("GET".CompareTo(testLink.Method) == 0);
            Assert.IsTrue(testLink.Relation.CompareTo("field") == 0);
        }
Example #12
0
        public void urlForRelatedResource_UT()
        {
            string expectEdUrl = @"/api/item/4";
            string testURL     = "";

            Item testItem = new Item();

            testItem.ItemId = 4;
            testItem.Name   = "Test item";

            OrderLine testOrderLine = new OrderLine();

            testOrderLine.OrderLineId = 182;
            testOrderLine.OrderItem   = testItem;

            List <PropertyInfo> propList = testOrderLine.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(RelatedResource))).ToList <PropertyInfo>();

            foreach (PropertyInfo p in propList)
            {
                UrlFactory urlGenerator = new UrlFactory(@"/api");
                testURL = urlGenerator.generateUrl(p.GetValue(testOrderLine, null));
            }

            Assert.IsTrue(expectEdUrl.CompareTo(testURL) == 0);
        }
Example #13
0
        protected override void Render(HtmlTextWriter writer)
        {
            if (relatedStory == null)
            {
                return;
            }

            if (!String.IsNullOrEmpty(this.Title))
            {
                writer.WriteLine(@"<div class=""PageSmallCaption"">{0}</div>", this.Title);
            }

            writer.WriteLine("<ul id=\"relatedStoriesList\">");

            foreach (Story s in relatedStory)
            {
                Category category     = CategoryCache.GetCategory(s.CategoryID, KickPage.HostProfile.HostID);
                string   kickStoryUrl =
                    UrlFactory.CreateUrl(UrlFactory.PageName.ViewStory, s.StoryIdentifier, category.CategoryIdentifier);

                writer.WriteLine("<li><a href=\"{0}\">{1}</a></li>", kickStoryUrl, s.Title);
            }

            writer.WriteLine("</ul>");
        }
Example #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.hypSiteTitle.NavigateUrl  = UrlFactory.CreateUrl(UrlFactory.PageName.Home);
            this.hypSiteTitle.Text         = this.KickPage.HostProfile.SiteTitle;
            this.litSiteTagLine.Text       = this.KickPage.HostProfile.TagLine;
            this.litFeedBurnerCounter.Text = this.KickPage.HostProfile.FeedBurnerMainRssFeedCountHtml;

            this.pnlSideAds.Visible = this.KickPage.DisplaySideAds;

            this.googleTop.AdSenseId  = this.KickPage.AdSenseID;
            this.googleSide.AdSenseId = this.KickPage.AdSenseID;

            if (this.KickPage.DisplayAnnouncement && !String.IsNullOrEmpty(this.KickPage.HostProfile.AnnouncementHtml))
            {
                this.pnlSiteAnnouncement.Visible = true;
                this.litSiteAnnouncement.Text    = this.KickPage.HostProfile.AnnouncementHtml;
            }

            if (this.KickPage.Caption.Length > 0)
            {
                this.pnlPageCaption.Visible = true;
                this.litPageCaption.Text    = this.KickPage.Caption;
                this.RssFeedIcon.Visible    = this.KickPage.HasRssFeed;
            }
        }
        protected override void Render(HtmlTextWriter writer)
        {
            if (this._tags.Count == 0)
            {
                writer.WriteLine("");
            }
            else
            {
                string tagClass; bool isEven = false;
                foreach (WeightedTag tag in this._tags)
                {
                    string spanID = this._storyID + "_" + tag.TagID + "_EditableTag";
                    if (isEven)
                    {
                        tagClass = "evenTag";
                    }
                    else
                    {
                        tagClass = "oddTag";
                    }

                    writer.WriteLine(@"<span class=""EditableTag {3}"" id=""{0}""><a href=""{1}"" class=""tag {3}"">{2}</a>",
                                     spanID, UrlFactory.CreateUrl(UrlFactory.PageName.UserTag, _username, tag.TagIdentifier), tag.TagName, tagClass);

                    writer.WriteLine(@" [<a href=""javascript:RemoveUserStoryTag({0}, {1});"">x</a>]<br /></span>",
                                     this._storyID, tag.TagID);
                    isEven = !isEven;
                }
            }
        }
        public IHttpActionResult UpdateTestScript(int testScriptId, TestScript model)
        {
            model.CreatedByUserId = base.UserId;
            if (testScriptId != model.TestScriptId)
            {
                return(NotFound());
            }
            if (model.StoryId <= 0)
            {
                ModelState.AddModelError("Story", "StoryId is required");
            }

            if (ModelState.IsValid)
            {
                var dbScript = _repoFactory.TestScripts.GetTestScripts(model.StoryId, testScriptId)?.FirstOrDefault();
                if (dbScript == null)
                {
                    return(BadRequest());
                }

                model.LastModifiedBy = base.UserId;
                model.LastModifiedOn = DateTime.Now;

                _repoFactory.TestScripts.UpdateTestScript(model);

                UpdateTestScriptAssigneeMapping(testScriptId, model.AssignedToDeveloperId, model.AssignedToDevManagerId, model.AssignedToBusinessAnalystId,
                                                model.AssignedToBusinessStakeholderId);

                if (!string.IsNullOrWhiteSpace(model.AssignedToDeveloperId) &&
                    !string.Equals(model.AssignedToDeveloperId, UserId, StringComparison.OrdinalIgnoreCase) &&
                    !string.Equals(dbScript.DeveloperId, model.AssignedToDeveloperId, StringComparison.OrdinalIgnoreCase))
                {
                    var receipientName = _cacheService.GetUserName(model.AssignedToDeveloperId);
                    if (!string.IsNullOrWhiteSpace(receipientName))
                    {
                        var receipient     = new MailUser(model.AssignedToDeveloperId, receipientName);
                        var actor          = new MailUser(UserId, DisplayName);
                        var testScriptLink = UrlFactory.GetTestScriptPageUrl(model.StoryId, model.TestScriptId);
                        _emailService.SendMail(receipient, Core.Enumerations.EmailType.TestScriptAssigned, actor, testScriptLink);
                    }
                }
                var approveStatusId = GetTestScriptApproveStatusId();
                if (dbScript.TestScriptStatus != approveStatusId && model.TestScriptStatus == approveStatusId &&
                    !string.IsNullOrWhiteSpace(model.AssignedToDeveloperId) &&
                    !string.Equals(model.AssignedToDeveloperId, UserId, StringComparison.OrdinalIgnoreCase))
                {
                    var receipientName = _cacheService.GetUserName(model.AssignedToDeveloperId);
                    if (!string.IsNullOrWhiteSpace(receipientName))
                    {
                        var receipient     = new MailUser(model.AssignedToDeveloperId, receipientName);
                        var actor          = new MailUser(UserId, DisplayName);
                        var testScriptLink = UrlFactory.GetTestScriptPageUrl(model.StoryId, model.TestScriptId);
                        _emailService.SendMail(receipient, Core.Enumerations.EmailType.TestScriptApproved, actor, testScriptLink);
                    }
                }

                return(Ok());
            }
            return(BadRequest(ModelState));
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            Enum.TryParse(Location, out _location);
            var serviceUrl = new Uri(string.Format(UrlFactory.BaseUrl, Organization, _location, UrlFactory.OrgServiceQueryPath));

            // OAuth authentication, data connection
            if (ParameterSetName == "oauthdata")
            {
                var endpoint = UrlFactory.GetDiscoveryUrl(serviceUrl, ApiType.CustomerEngagement);
                var auth     = new OAuthHelper(endpoint, ClientId, RedirectUri);
                var service  = CrmConnection.GetConnection(serviceUrl, auth.AuthResult.AccessToken);
                SessionState.PSVariable.Set(SessionVariableFactory.OAuthData, auth);
                SessionState.PSVariable.Set(SessionVariableFactory.DataConnection, service);
            }
            // Cookie authentication, data connection
            else if (ParameterSetName == "webauth")
            {
                Enum.TryParse(AuthType, out Models.AuthenticationType authType);
                var webAuthCookies = WebAuthHelper.GetAuthenticatedCookies(serviceUrl.ToString(), authType);
                var service        = CrmConnection.GetConnection(serviceUrl, webAuthCookies);
                SessionState.PSVariable.Set(SessionVariableFactory.WebCookies, webAuthCookies);
                SessionState.PSVariable.Set(SessionVariableFactory.DataConnection, service);
            }
            // OAuth authentication, admin API
            else if (ParameterSetName == "oauthadmin")
            {
                serviceUrl = UrlFactory.GetServiceUrl(_location);
                var endpoint = UrlFactory.GetDiscoveryUrl(serviceUrl, ApiType.Admin);
                var auth     = new OAuthHelper(endpoint, ClientId, RedirectUri);
                SessionState.PSVariable.Set(SessionVariableFactory.OAuthAdmin, auth);
            }
        }
 //NOTE: GJ: this page will be depreciated in favour of tagging
 protected void Page_Init(object sender, EventArgs e)
 {
     this.Caption    = "Latest " + CategoryCache.GetCategory(this.UrlParameters.CategoryID, this.HostProfile.HostID).Name + " stories";
     this.Title      = this.HostProfile.SiteTitle + " - " + this.Caption;
     this.PageName   = UrlFactory.PageName.ViewCategory;
     this.RssFeedUrl = UrlFactory.CreateUrl(UrlFactory.PageName.ViewCategoryRss, this.UrlParameters.CategoryIdentifier);
 }
        public async Task PostNewNoteActivity(Note note, string username, string noteId, string targetHost, string targetInbox)
        {
            try
            {
                var actor   = UrlFactory.GetActorUrl(_instanceSettings.Domain, username);
                var noteUri = UrlFactory.GetNoteUrl(_instanceSettings.Domain, username, noteId);

                var now       = DateTime.UtcNow;
                var nowString = now.ToString("s") + "Z";

                var noteActivity = new ActivityCreateNote()
                {
                    context   = "https://www.w3.org/ns/activitystreams",
                    id        = $"{noteUri}/activity",
                    type      = "Create",
                    actor     = actor,
                    published = nowString,

                    to       = note.to,
                    cc       = note.cc,
                    apObject = note
                };

                await PostDataAsync(noteActivity, targetHost, actor, targetInbox);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error sending {Username} post ({NoteId}) to {Host}{Inbox}", username, noteId, targetHost, targetInbox);
                throw;
            }
        }
        protected void SubmitStory_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (!KickPage.KickUserProfile.IsVetted)
                {
                    throw new SecurityException("This user can't submit stories");
                }

                short  categoryID      = short.Parse(Category.SelectedValue);
                string storyIdentifier =
                    StoryBR.AddStory(KickPage.HostProfile.HostID, Title.Text, Description.Text, Url.Text, categoryID,
                                     KickPage.KickUserProfile, KickPage.IPAddress);

                NewStoryPanel.Visible = false;
                SuccessPanel.Visible  = true;

                string categoryName = CategoryCache.GetCategory(categoryID, KickPage.HostProfile.HostID).CategoryIdentifier;
                UpcomingStoryQueue.NavigateUrl = UrlFactory.CreateUrl(UrlFactory.PageName.NewStories);
                UpcomingStoryQueue.Text        = "upcoming queue";
                StoryLink.NavigateUrl          = UrlFactory.CreateUrl(UrlFactory.PageName.ViewStory, storyIdentifier, categoryName);

                // Bind the story original url to the image customization user control
                KickItImagePersonalization.StoryUrl = Url.Text;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!KickPage.KickUserProfile.IsVetted)
            {
                Response.Redirect(UrlFactory.CreateUrl(UrlFactory.PageName.UserTest, KickPage.KickUserProfile.Username));
            }

            if (!Page.IsPostBack)
            {
                // In case a url is passed on the querystring check if the story
                // already exists and in that case redirect the user to the story page
                string url = Request.QueryString["url"];

                if (!string.IsNullOrEmpty(url))
                {
                    Dal.Story story = Incremental.Kick.Dal.Story.FetchStoryByUrl(url.Trim());

                    if (story != null)
                    {
                        Response.Redirect(
                            UrlFactory.CreateUrl(UrlFactory.PageName.ViewStory, story.StoryIdentifier,
                                                 story.Category.CategoryIdentifier), true);
                    }
                }

                // Bind list of categories
                Category.DataSource = CategoryCache.GetCategories(KickPage.HostProfile.HostID);
                Category.DataBind();

                // Retrieve story information if story was submitted with the bookmarklet
                Url.Text   = Request.QueryString["url"];
                Title.Text = Request.QueryString["title"];

                if (Title.Text.Length > 70)
                {
                    Title.Text = Title.Text.Substring(0, 70);
                }

                if (Title.Text.Length > 0)
                {
                    TitleNoteLabel.Text    = "NOTE: Is this title correct?<br/>";
                    TitleNoteLabel.Visible = true;
                }

                Description.Text = Request.QueryString["description"];

                if (Url.Text.Length == 0)
                {
                    Url.Focus();
                }
                else if (Title.Text.Length == 0)
                {
                    Title.Focus();
                }
                else
                {
                    Description.Focus();
                }
            }
        }
        protected void UrlCheck_ServerValidate(object source, ServerValidateEventArgs args)
        {
            // Retrieve the story given the url
            Dal.Story story = Incremental.Kick.Dal.Story.FetchStoryByUrl(args.Value);

            // If the story already exists in the database
            if (story != null)
            {
                // Make page invalid
                args.IsValid = false;

                // Let user kick the existing story by providing a link to it
                UrlCheck.ErrorMessage =
                    string.Format("The story already exists. You might want to <a href=\"{0}\">kick it</a> instead.<br/>",
                                  UrlFactory.CreateUrl(UrlFactory.PageName.ViewStory, story.StoryIdentifier,
                                                       story.Category.CategoryIdentifier));
                return;
            }

            // check to see its bannination status
            bool banninated = BannedUrlHelper.IsUrlBanninated(args.Value, HostCache.GetHost(HostHelper.GetHostAndPort(Request.Url)).HostID);

            // If the url matches
            if (banninated)
            {
                // Make page invalid
                args.IsValid = false;

                // Let user kick the existing story by providing a link to it
                UrlCheck.ErrorMessage = "This URL cannot be submitted.<br/>";
            }
        }
        public IHttpActionResult UpdateProjectStory(int projectId, int storyId, UserStory model)
        {
            if (projectId != model.ProjectId || storyId != model.StoryId)
            {
                return(NotFound());
            }
            if (ModelState.IsValid)
            {
                var dbStory = _repoFactory.ProjectStories.GetProjectStories(projectId)
                              ?.SingleOrDefault(s => s.StoryId == storyId);
                if (dbStory == null)
                {
                    return(BadRequest());
                }

                var transaction = _repoFactory.BeginTransaction();
                try
                {
                    _repoFactory.ProjectStories.UpdateProjectStory(model, transaction);

                    _repoFactory.Sprints.DeleteStorySprintMapping(model.StoryId, transaction);
                    if (!string.IsNullOrWhiteSpace(model.SprintIds))
                    {
                        var sprintIds = model.SprintIds.Split(',');
                        foreach (var s in sprintIds)
                        {
                            if (int.TryParse(s, out var sprintId))
                            {
                                _repoFactory.Sprints.AddStoryToSprint(sprintId, model.StoryId, transaction);
                            }
                        }
                    }

                    _repoFactory.CommitTransaction();

                    if (!string.IsNullOrWhiteSpace(model.AssignedToUserId) &&
                        !string.Equals(model.AssignedToUserId, UserId, System.StringComparison.OrdinalIgnoreCase) &&
                        !string.Equals(dbStory.AssignedToUserId, model.AssignedToUserId, System.StringComparison.OrdinalIgnoreCase))
                    {
                        var receipientName = _cacheService.GetUserName(model.AssignedToUserId);
                        if (!string.IsNullOrWhiteSpace(receipientName))
                        {
                            var receipient    = new MailUser(model.AssignedToUserId, receipientName);
                            var actor         = new MailUser(UserId, DisplayName);
                            var userStoryLink = UrlFactory.GetUserStoryPageUrl(projectId, model.StoryId);
                            _emailService.SendMail(receipient, Core.Enumerations.EmailType.UserStoryAssigned, actor, userStoryLink);
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    _repoFactory.RollbackTransaction();
                    _logger.Error(ex, Request.RequestUri.ToString());
                    return(InternalServerError(ex));
                }
                return(Ok());
            }
            return(BadRequest(ModelState));
        }
Example #24
0
        public Note GetStatus(string username, ExtractedTweet tweet)
        {
            var actorUrl = UrlFactory.GetActorUrl(_instanceSettings.Domain, username);
            var noteUrl  = UrlFactory.GetNoteUrl(_instanceSettings.Domain, username, tweet.Id.ToString());

            var to       = $"{actorUrl}/followers";
            var apPublic = "https://www.w3.org/ns/activitystreams#Public";

            var extractedTags = _statusExtractor.Extract(tweet.MessageContent);

            _statisticsHandler.ExtractedStatus(extractedTags.tags.Count(x => x.type == "Mention"));

            // Replace RT by a link
            var content = extractedTags.content;

            if (content.Contains("{RT}") && tweet.IsRetweet)
            {
                if (!string.IsNullOrWhiteSpace(tweet.RetweetUrl))
                {
                    content = content.Replace("{RT}",
                                              $@"<a href=""{tweet.RetweetUrl}"" rel=""nofollow noopener noreferrer"" target=""_blank"">RT</a>");
                }
                else
                {
                    content = content.Replace("{RT}", "RT");
                }
            }

            string inReplyTo = null;

            if (tweet.InReplyToStatusId != default)
            {
                inReplyTo = $"https://{_instanceSettings.Domain}/users/{tweet.InReplyToAccount.ToLowerInvariant()}/statuses/{tweet.InReplyToStatusId}";
            }

            var note = new Note
            {
                id = noteUrl,

                published    = tweet.CreatedAt.ToString("s") + "Z",
                url          = noteUrl,
                attributedTo = actorUrl,

                inReplyTo = inReplyTo,
                //to = new [] {to},
                //cc = new [] { apPublic },

                to = new[] { to },
                //cc = new[] { apPublic },
                cc = new string[0],

                sensitive  = false,
                content    = $"<p>{content}</p>",
                attachment = Convert(tweet.Media),
                tag        = extractedTags.tags
            };

            return(note);
        }
Example #25
0
 protected void Page_Init(object sender, EventArgs e)
 {
     this.Caption    = "Stories recently tagged with '" + this.UrlParameters.TagIdentifier + "'";
     this.Title      = this.HostProfile.SiteTitle + " : " + this.Caption;
     this.PageName   = UrlFactory.PageName.ViewTag;
     this.DisplayAds = true;
     this.RssFeedUrl = UrlFactory.CreateUrl(UrlFactory.PageName.ViewTagRss, this.UrlParameters.TagIdentifier);
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     this.StoryList.DataBind(StoryCache.GetCategoryStories(this.UrlParameters.CategoryID, true, this.HostProfile.HostID, this.UrlParameters.PageNumber, this.UrlParameters.PageSize));
     this.Paging.RecordCount = StoryCache.GetCategoryStoryCount(this.UrlParameters.CategoryID, true, this.HostProfile.HostID);
     this.Paging.PageNumber  = UrlParameters.PageNumber;
     this.Paging.PageSize    = UrlParameters.PageSize;
     this.Paging.BaseUrl     = UrlFactory.CreateUrl(UrlFactory.PageName.ViewCategory, this.UrlParameters.CategoryIdentifier);
 }
Example #27
0
 protected void Page_Load(object sender, EventArgs e)
 {
     this.StoryList.DataBind(StoryCache.GetTaggedStories(this.UrlParameters.TagIdentifier, this.HostProfile.HostID, this.UrlParameters.PageNumber, this.UrlParameters.PageSize));
     this.Paging.RecordCount = StoryCache.GetTaggedStoryCount(this.UrlParameters.TagIdentifier, this.HostProfile.HostID);
     this.Paging.PageNumber  = UrlParameters.PageNumber;
     this.Paging.PageSize    = UrlParameters.PageSize;
     this.Paging.BaseUrl     = UrlFactory.CreateUrl(UrlFactory.PageName.ViewTag, HttpUtility.UrlEncode(this.UrlParameters.TagIdentifier));
 }
Example #28
0
        public ApiStory ToApi()
        {
            Host host = HostCache.GetHost(this.HostID);

            return(new ApiStory(
                       this.Title, host.RootUrl + UrlFactory.CreateUrl(UrlFactory.PageName.ViewStory, this.StoryIdentifier, CategoryCache.GetCategory(this.CategoryID, this.HostID).CategoryIdentifier), this.Description,
                       this.CreatedOn, this.PublishedOn, this.IsPublishedToHomepage, this.KickCount, this.CommentCount, UserCache.GetUser(this.UserID).ToApi(host)));
        }
Example #29
0
        protected override void OnInit(EventArgs e)
        {
            this.Caption    = this.UrlParameters.UserIdentifier;
            this.Title      = this.HostProfile.SiteTitle + " : " + this.Caption;
            this.RssFeedUrl = UrlFactory.CreateUrl(UrlFactory.PageName.UserKickedStoriesRss, this.UrlParameters.UserIdentifier);
            this.DisplayAds = false;

            base.OnInit(e);
        }
Example #30
0
        public void getUrlsforRelatedResourceCollection_UT()
        {
            //Declare test items
            Item testItem1 = new Item();

            testItem1.ItemId = 4;
            testItem1.Name   = "Test item";

            Item testItem2 = new Item();

            testItem2.ItemId = 777;
            testItem2.Name   = "Bacon";

            //Declare OrderLines
            OrderLine ol1 = new OrderLine(testItem1);

            ol1.OrderLineId = 1;

            OrderLine ol2 = new OrderLine(testItem2);

            ol2.OrderLineId = 24;


            //Declare new order and add hte orderlines to the orderline list
            Order newOrder = new Order();

            newOrder.OrderLines.Add(ol1);
            newOrder.OrderLines.Add(ol2);

            List <string> urlsForOrderLines = new List <string>();



            PropertyInfo pInfo           = newOrder.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(RelatedResource))).FirstOrDefault();
            Object       relatedResource = pInfo.GetValue(newOrder, null);

            if (relatedResource is IEnumerable)
            {
                foreach (var ele in (IEnumerable)relatedResource)
                {
                    UrlFactory urlGenerator = new UrlFactory(@"/api");
                    string     url          = urlGenerator.generateUrl(ele);
                    urlsForOrderLines.Add(url);
                }
            }

            foreach (string olURL in urlsForOrderLines)
            {
                string expectEdUrl1 = @"/api/orderlines/1";
                string expectEdUrl2 = @"/api/orderlines/24";

                if (olURL.CompareTo(expectEdUrl1) != 0 && olURL.CompareTo(expectEdUrl2) != 0)
                {
                    Assert.Fail("Urls are incorrect");
                }
            }
        }