Esempio n. 1
0
 public PostSummary(string URLTitle, DateTime date, PostType type)
 {
     PartitionKey= date.Year.ToString();
     RowKey = URLTitle;
     Type = type;
     Date = date;
 }
Esempio n. 2
0
        public async Task <bool> AddToFavourite(User user, PostType postType, string postId)
        {
            if (user is null)
            {
                return(false);
            }

            string postIdComplate = ',' + postId;

            switch (postType)
            {
            case PostType.Company: user.FavouriteCompanies += postIdComplate;
                break;

            case PostType.Contestant: user.FavouriteContestants += postIdComplate;
                break;

            case PostType.Job: user.FavouriteJobs += postIdComplate;
                break;
            }

            user.ActivityReaded = false;
            await _userManager.UpdateAsync(user);

            return(true);
        }
Esempio n. 3
0
        public async Task <IActionResult> Edit(int?id, [FromBody] PostType postType)
        {
            try
            {
                if (id == null)
                {
                    return(BadRequest());
                }
                else
                {
                    var postTypeToUpdate = _context.PostTypes.FirstOrDefault(p => p.PostTypeId == id);
                    if (postTypeToUpdate == null)
                    {
                        return(NotFound());
                    }
                    else
                    {
                        postTypeToUpdate.CreatedDate           = postType.CreatedDate;
                        postTypeToUpdate.PostTypeName          = postType.PostTypeName;
                        postTypeToUpdate.SortOrder             = postType.SortOrder;
                        postTypeToUpdate.ModifiedDate          = DateTime.Now;
                        _context.Entry(postTypeToUpdate).State = EntityState.Modified;
                        await _context.SaveChangesAsync();

                        return(new ObjectResult(postTypeToUpdate));
                    }
                }
            }
            catch
            {
                return(BadRequest());
            }
        }
Esempio n. 4
0
        public async Task LoadMorePosts(
            PostType type, int count, int offset)
        {
            ShowLoadingMoreGrid();

            try
            {
                var result = await PostApi.Get(
                    SettingsManager.PersistentSettings.CurrentUser.Token,
                    type, count, offset)
                             .ConfigureAwait(true);

                if (result == null)
                {
                    return;
                }

                result.Data ??= new List <PostSchema>();

                await AddMorePosts(result.Data)
                .ConfigureAwait(true);
            }
            finally
            {
                HideLoadingMoreGrid();
            }
        }
Esempio n. 5
0
        // GET: BlogEntries
        public ActionResult Index(PostType PostType)
        {
            ViewBag.topics = PostType.topics;
            ViewBag.Author = db.Users.Where(u => u.Id == db.Posts.FirstOrDefault().AuthorId).FirstOrDefault().DisplayName;
            if (PostType == PostType.date)
            {
                //ViewBag.Date = PostType.Remove(0, 4).Split({20, 21});
                ViewBag.PostType = PostType;
                ViewBag.topics   = PostType.topics;
                var indexedPosts = db.Posts.Where(p => p.CreationDate.Year == 2020).ToList();
                return(View(indexedPosts));
            }
            if (PostType == PostType.topics)
            {
                var indexedPosts = db.Posts.Where(p => p.Published == true);
                ViewBag.Topic0   = PostType.MVC;
                ViewBag.Topic1   = PostType.Photography;
                ViewBag.Topic2   = PostType.TED_Talks;
                ViewBag.Topic3   = PostType.Brain_Teasers;
                ViewBag.PostType = PostType.topics;
                ViewBag.topics   = PostType.topics;

                return(View(indexedPosts));
            }
            else
            {
                var indexedPosts = db.Posts.Where(p => p.PostType == PostType).ToList().Where(p => p.Published == true);
                ViewBag.Topic    = PostType;
                ViewBag.PostType = PostType;
                return(View(indexedPosts));
            }
        }
Esempio n. 6
0
        public AliExpressPoster(
            string restAPIUrl,
            string restAPIKey,
            string restAPISecret,
            PostType postType,
            double priceMarkupPercentage,
            double usdToMyrCurrencyRate,
            double productMinPriceAfterConvert,
            double productBelowMinMarkup)
        {
            this.restAPIKey                  = restAPIKey;
            this.restAPISecret               = restAPISecret;
            this.postType                    = postType;
            this.priceMarkupPercentage       = priceMarkupPercentage;
            this.usdToMyrCurrencyRate        = usdToMyrCurrencyRate;
            this.productMinPriceAfterConvert = productMinPriceAfterConvert;
            this.productBelowMinMarkup       = productBelowMinMarkup;

            RestAPI rest = new RestAPI(
                restAPIUrl,
                this.restAPIKey,
                this.restAPISecret);

            wc = new WCObject(rest);
        }
Esempio n. 7
0
        public static void UpdatePostType(PostType postType, out StringBuilder errors)
        {
            errors = new StringBuilder();

            try
            {
                using (var db = new ApplicationDbContext())
                {
                    var fetchedPostType = GetPostTypeById(postType.Id);

                    if (fetchedPostType == null)
                    {
                        errors.Append("Post Type does not exist.\n");
                        return;
                    }

                    fetchedPostType.Slug        = postType.Slug;
                    fetchedPostType.Category    = postType.Category;
                    fetchedPostType.SubCategory = postType.SubCategory;

                    db.PostTypes.AddOrUpdate(fetchedPostType);
                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Esempio n. 8
0
        private Response Post(string stepName, string url, object parameters, PostType type)
        {
            RecordStepStart(stepName);

            var client = GetWebClient();

            try
            {
                switch (type)
                {
                case PostType.Form:
                    _data = client.UploadValues(url, NameValueCollectionConversions.ConvertFromObject(parameters));
                    break;

                case PostType.Json:
                    var serializer = new JavaScriptSerializer();
                    client.Headers.Add("Content-Type", "application/json; charset=utf-8");
                    _data = client.UploadData(url, Encoding.UTF8.GetBytes(serializer.Serialize(parameters)));
                    client.Headers.Remove("Content-Type");
                    break;
                }

                return(BuildResponse(client.Response));
            }
            catch (WebException)
            {
                return(BuildErrorResponse());
            }
            finally
            {
                RecordStepEnd(stepName);
            }
        }
Esempio n. 9
0
 public static void WriteJson(this PostType value, JsonWriter writer, JsonSerializer serializer)
 {
     switch (value)
     {
     case PostType.Post: serializer.Serialize(writer, "post"); break;
     }
 }
 public PostPerson(long personId, long postId, long levelId, PostType postType)
 {
     PersonId = personId;
     PostId   = postId;
     if (postType == PostType.CentralOrganization)
     {
         CentralOrganizationId = levelId;
     }
     else if (postType == PostType.BranchProvince)
     {
         BranchProvinceId = levelId;
     }
     else if (postType == PostType.University)
     {
         UniversityId = levelId;
     }
     else if (postType == PostType.College)
     {
         CollegeId = levelId;
     }
     else if (postType == PostType.EducationalGroup)
     {
         EducationalGroupId = levelId;
     }
     else if (postType == PostType.FieldofStudy)
     {
         FieldofStudyId = levelId;
     }
 }
Esempio n. 11
0
        public async Task <List <Notice> > GetUpcomingEvents(int page, PostType all)
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var resp   = await _noticeService.GetUpcomingEvents(userId);

            return(resp);
        }
Esempio n. 12
0
 /// <summary>
 /// Additional default constructer to define a place with specific type of related posts..
 /// for ex: place with mistakes only, or place with supplications only. etc..
 /// </summary>
 /// <param name="postDataType"> that has post and anlylize its content</param>
 /// <param name="relatedPostFilter"> the type of related posts which we need the filter with it</param>
 public PlaceDetailsPage(PostDataType postDataType, PostType relatedPostFilter, string title)
 {
     postData      = postDataType;
     relatedFilter = relatedPostFilter;
     this.Title    = title;
     Init();
 }
Esempio n. 13
0
 public PlaceDetailsPage(PostDataType postDataType)
 {
     postData      = postDataType;
     relatedFilter = PostType.Place;// default filter is place whear everyting is showing
     this.Title    = postData.Title;
     Init();
 }
Esempio n. 14
0
 /// <summary>
 /// 创建新的帖子编辑模型
 /// </summary>
 public async Task <PostEditModel> CreateNewEditModelAsync(PostType defaultType, PersonView person)
 {
     if (person == null)
     {
         throw new ArgumentNullException(nameof(person));
     }
     using (var work = this.dbFactory.StartWork())
     {
         PostEditModel model = new PostEditModel();
         model.PostType = defaultType;
         // 创建话题列表
         model.TopicSelectItems.Add(new SelectListItem("选择话题分类...", ""));
         List <Topic> topics = new List <Topic>();
         if (person.RoleType == RoleType.Admin || person.RoleType == RoleType.SuperAdmin)
         {
             topics = await work.Topic.GetAllAsync(SearchType.Visible, true);
         }
         else
         {
             topics = await work.Topic.GetAllAsync(SearchType.Visible, false);
         }
         foreach (var topic in topics)
         {
             model.TopicSelectItems.Add(new SelectListItem(topic.Name, topic.Id.ToString()));
         }
         ;
         List <string> BestTags = (await work.Tag.GetBestAsync()).Select(p => p.Name).ToList();
         model.BestTags = JsonConvert.SerializeObject(BestTags);
         return(model);
     }
 }
Esempio n. 15
0
        public async Task <IEnumerable <PostPreviewDto> > GetSimilarPosts(PostType type = PostType.None)
        {
            int number = type == PostType.None ? 6 : 3;
            var posts  = await _getRandomPostPreviewsQueryHandler.HandleAsync(new GetRandomPostPreviewsQuery(type, number));

            return(posts);
        }
Esempio n. 16
0
        /// <summary>
        /// FORM表单解析
        /// </summary>
        /// <param name="dataToType"></param>
        internal void ParseForm(PostType dataToType = PostType.Data)
        {
            switch (HttpHeader.PostType)
            {
            case PostType.Json: Form.SetText(GetFormText(), Http.Header.QueryJsonNameChar); return;

            case PostType.Xml: Form.SetText(GetFormText(), Http.Header.QueryXmlNameChar); return;

            case PostType.Data:
                if (FormBufferReceiveEndIndex == 0)
                {
                    return;
                }
                switch (dataToType)
                {
                case PostType.Json: Form.SetText(GetFormText(), Http.Header.QueryJsonNameChar); return;

                case PostType.Xml: Form.SetText(GetFormText(), Http.Header.QueryXmlNameChar); return;

                default: return;
                }

            default: Form.Parse(); return;
            }
        }
Esempio n. 17
0
 public static PostTypeDto ToDto(PostType postType)
 {
     return(new PostTypeDto
     {
         PostType = postType.PostTypeValue
     });
 }
Esempio n. 18
0
 public string PostString(string data, PostType postType, string contentType = null)
 {
     try
     {
         Request.Method      = "POST";
         Request.ContentType = contentType ?? "application/json";
         if (postType == PostType.Byte)
         {
             byte[] byteArray = Encoding.ASCII.GetBytes(data);
             Request.ContentLength = byteArray.Length;
             Stream inStream = Request.GetRequestStream();
             inStream.Write(byteArray, 0, byteArray.Length);
             inStream.Close();
         }
         else
         {
             Request.ContentLength = data.Length;
             Stream       inStream    = Request.GetRequestStream();
             StreamWriter writeStream = new StreamWriter(inStream);
             writeStream.Write(data);
             writeStream.Flush();
         }
         var response = (HttpWebResponse)Request.GetResponse();
         using (Stream rpRead = response.GetResponseStream())
         {
             StreamReader stReader = new StreamReader(rpRead, Encoding.ASCII);
             string       outPutRD = stReader.ReadToEnd().Trim();
             return(outPutRD);
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
Esempio n. 19
0
 public Post(User owner, PostType type, string fileName, DateTime postedDate)
 {
     Owner      = owner;
     Type       = type;
     FileName   = fileName;
     PostedDate = postedDate;
 }
Esempio n. 20
0
        public PostData(T item)
        {
            var boxedType = item.GetType();

            if (typeof(byte[]).AssignableFrom(boxedType))
            {
                WrittenBytes = item as byte[]; Type = PostType.ByteArray;
            }
            else if (typeof(string).AssignableFrom(boxedType))
            {
                _literalString = item as string; Type = PostType.LiteralString;
            }
            else if (typeof(IEnumerable <string>).AssignableFrom(boxedType))
            {
                _enumurabeOfStrings = (IEnumerable <string>)item; Type = PostType.EnumerableOfString;
            }
            else if (typeof(IEnumerable <object>).AssignableFrom(boxedType))
            {
                _enumerableOfObject = (IEnumerable <object>)item; Type = PostType.EnumerableOfObject;
            }
            else
            {
                _serializable = item; Type = PostType.Serializable;
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Delete User Action Activity Log
        /// </summary>
        /// <param name=></param>
        /// <returns>bool</returns>
        public async Task <bool> DeletePostType(int PostTypeId)
        {
            #region Declare a return type with initial value.
            bool isPostTypeDeleted = default(bool);
            #endregion
            try
            {
                if (PostTypeId > default(int))
                {
                    #region Vars
                    PostType PostType = null;
                    #endregion
                    #region Get PostType by id
                    PostType = await UnitOfWork.PostTypeRepository.GetById(PostTypeId);

                    #endregion
                    #region check if object is not null
                    if (PostType != null)
                    {
                        PostType.IsDeleted = (byte)DeleteStatusEnum.Deleted;
                        #region Apply the changes to the database
                        UnitOfWork.PostTypeRepository.Update(PostType);
                        isPostTypeDeleted = await UnitOfWork.Commit() > default(int);

                        #endregion
                    }
                    #endregion
                }
            }
            catch (Exception exception)
            {
            }
            return(isPostTypeDeleted);
        }
Esempio n. 22
0
        public async Task CreateMethodShouldAddPostInDatabase(string title, PostType type, string description, int categoryId)
        {
            var guid = Guid.NewGuid().ToString();

            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(guid)
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();
            var usersServiceMock = new Mock <IUsersService>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));
            usersServiceMock.Setup(us => us.AddPointsAsync(guid, 1)).ReturnsAsync(1);

            var postsService = new PostsService(db, null, usersServiceMock.Object, dateTimeProvider.Object);

            var expectedIds = new[] { 1, 2, 3 };
            var postId      = await postsService.CreateAsync(title, type, description, guid, categoryId, expectedIds);

            var actual = await db.Posts.FirstOrDefaultAsync();

            var actualTagIds = actual.Tags.Select(t => t.TagId).ToArray();

            postId.Should().Be(1);
            db.Posts.Should().HaveCount(1);
            actualTagIds.Should().BeEquivalentTo(expectedIds);
        }
Esempio n. 23
0
        public override MvcHtmlString WriteButton(HtmlHelper helper, object htmlAttributes)
        {
            // Provide default value for PostUrl in case it hasn't been specified.
            if (string.IsNullOrWhiteSpace(PostUrl))
            {
                UrlHelper Url = new UrlHelper(helper.ViewContext.RequestContext);
                PostUrl = Url.Action("Postback");
            }

            TagBuilder tb = new TagBuilder("input");

            tb.Attributes.Add("type", "button");
            tb.Attributes.Add("class", "ExpressFormsModifyDataButton");
            tb.Attributes.Add("value", Text);
            tb.Attributes.Add("data-posturl", PostUrl);
            tb.Attributes.Add("data-actiontype", ActionType.ToString());
            tb.Attributes.Add("data-posttype", PostType.ToString());
            tb.Attributes.Add("data-formname", FormName);
            tb.Attributes.Add("data-message", ConfirmationMessage);
            tb.Attributes.Add("data-id", Convert.ToString(IdForDeletion));
            tb.Attributes.Add("data-tableid", TableIdForDeletion);
            if (!IsVisible)
            {
                tb.Attributes.Add("style", "display: none;");
            }

            IDictionary <string, object> efHtmlAttributes = new RouteValueDictionary(htmlAttributes);

            foreach (var kvp in efHtmlAttributes)
            {
                tb.MergeAttribute(kvp.Key, Convert.ToString(kvp.Value));
            }

            return(new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing)));
        }
Esempio n. 24
0
        private bool isCheckin(string text, string source)
        {
            bool checkin = false;

            PostType pType = getPostType(source);

            switch (pType)
            {
            case PostType.Foursquare:
                checkin = true;
                break;

            case PostType.Instagram:
                checkin = false;
                break;

            case PostType.Twitter:
                checkin = false;
                break;

            case PostType.Other:
                checkin = false;
                break;

            default:
                break;
            }
            return(checkin);
        }
        private void SwitchSearchType(PostType postType)
        {
            if (postType == _presenter.PostType)
            {
                return;
            }
            _presenter.PostType = postType;
            switch (postType)
            {
            case PostType.Hot:
                hotConstrain.Active  = true;
                topConstraint.Active = newConstraint.Active = false;
                break;

            case PostType.New:
                newConstraint.Active = true;
                topConstraint.Active = hotConstrain.Active = false;
                break;

            case PostType.Top:
                topConstraint.Active = true;
                hotConstrain.Active  = newConstraint.Active = false;
                break;
            }
            UIView.Animate(0.2, 0, UIViewAnimationOptions.CurveEaseOut, () =>
            {
                View.LayoutIfNeeded();
            }, null);
            GetPosts(true, true);
        }
Esempio n. 26
0
 /// <summary>
 /// Constructor for attribute applied against a controller action method.  This
 /// will create test data using the values of the action.
 /// </summary>
 /// <param name="position">The position of the test relative to all other tests</param>
 /// <param name="formId">The name of the form that will be submitted</param>
 /// <param name="postType">The type of data to be posted to the controller action</param>
 /// <param name="response">The expected response for the result, 200, 404 etc</param>
 /// <param name="method">The web method used when submitting the test, GET, POST, PUT etc</param>
 /// <param name="inputData">The data that will be submitted for the test, this must be a colon seperated list of strings representing parameter values to be submitted or can also be raw json or XML.</param>
 /// <param name="searchData">A colon seperated list of string that can be searched for within the response after either a get or prior to data being submitted via a form.</param>
 /// <param name="submitSearchData">A colon seperated list of strings that can be searched for in the response after data has been submitted.</param>
 /// <param name="name">Name of the test, used to identify it, if not specified then the controller and action name will be used.</param>
 /// <param name="parameters">Name value pair of valid parameter values for this test</param>
 /// <param name="redirectUrl">The expected url where the response will be redirected to.</param>
 public SmokeTestAttribute(int response,
                           PostType postType       = PostType.Form,
                           string formId           = "",
                           int position            = 10000,
                           string method           = "",
                           string inputData        = "",
                           string searchData       = "",
                           string submitSearchData = "",
                           string name             = "",
                           string parameters       = "",
                           string redirectUrl      = "/")
 {
     IsFromControllerAction = true;
     Response         = response;
     PostType         = postType;
     Position         = position;
     Method           = method;
     InputData        = inputData;
     SubmitSearchData = submitSearchData;
     SearchData       = searchData;
     Name             = name;
     FormId           = formId;
     Parameters       = parameters;
     RedirectUrl      = redirectUrl;
 }
Esempio n. 27
0
        private void watcher_FileCreated(object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType == WatcherChangeTypes.Created)
            {
                try
                {
                    if (e.FullPath == m_shellContentMenuFilePath)
                    {
                        string _fileContents;

                        using (StreamReader _textFile = new StreamReader(m_shellContentMenuFilePath))
                        {
                            _fileContents = _textFile.ReadToEnd();
                        }

                        m_delayPostType    = PostType.Photo;
                        m_delayPostPicList = new List <string>
                        {
                            _fileContents
                        };
                    }
                }
                catch
                {
                }
            }

            File.Delete(m_shellContentMenuFilePath);
        }
        public async Task AddReactionFromPost(string UserId, int PostId, PostType postType, ReactionType reactionType)
        {
            var reaction = GetReaction(UserId, PostId, postType);

            if (reaction == null)
            {
                reaction = new Reaction
                {
                    UserId       = UserId,
                    PostId       = PostId,
                    PostType     = postType,
                    ReactionType = reactionType
                };

                _context.Reactions.Add(reaction);
            }
            else
            {
                if (reaction.ReactionType == reactionType)
                {
                    return;
                }
                reaction.ReactionType = reactionType;
                _context.Reactions.Update(reaction);
            }
            await _context.SaveChangesAsync();
        }
Esempio n. 29
0
 public override int GetHashCode()
 {
     unchecked
     {
         int result = Id.GetHashCode();
         result = (result * 397) ^ (Urn != null ? Urn.GetHashCode() : 0);
         result = (result * 397) ^ UserId.GetHashCode();
         result = (result * 397) ^ DateAdded.GetHashCode();
         result = (result * 397) ^ DateModified.GetHashCode();
         result = (result * 397) ^ (TargetUserId.HasValue ? TargetUserId.Value.GetHashCode() : 0);
         result = (result * 397) ^ (ForwardedPostId.HasValue ? ForwardedPostId.Value.GetHashCode() : 0);
         result = (result * 397) ^ OriginUserId.GetHashCode();
         result = (result * 397) ^ (OriginUserName != null ? OriginUserName.GetHashCode() : 0);
         result = (result * 397) ^ SourceUserId.GetHashCode();
         result = (result * 397) ^ (SourceUserName != null ? SourceUserName.GetHashCode() : 0);
         result = (result * 397) ^ (SubjectUrn != null ? SubjectUrn.GetHashCode() : 0);
         result = (result * 397) ^ (ContentUrn != null ? ContentUrn.GetHashCode() : 0);
         result = (result * 397) ^ (TrackUrns != null ? TrackUrns.GetHashCode() : 0);
         result = (result * 397) ^ (Caption != null ? Caption.GetHashCode() : 0);
         result = (result * 397) ^ CaptionUserId.GetHashCode();
         result = (result * 397) ^ (CaptionSourceName != null ? CaptionSourceName.GetHashCode() : 0);
         result = (result * 397) ^ (ForwardedPostUrn != null ? ForwardedPostUrn.GetHashCode() : 0);
         result = (result * 397) ^ PostType.GetHashCode();
         result = (result * 397) ^ (OnBehalfOfUserId.HasValue ? OnBehalfOfUserId.Value.GetHashCode() : 0);
         return(result);
     }
 }
 /// <summary>
 /// Returns a pageable collection of entries ordered by the id descending.
 /// This is used in the admin section.
 /// </summary>
 public override IPagedCollection <EntryStatsView> GetEntries(PostType postType, int?categoryId, int pageIndex, int pageSize)
 {
     using (IDataReader reader = _procedures.GetEntries(BlogId, categoryId, pageIndex, pageSize, (int)postType))
     {
         return(reader.ReadPagedCollection(r => reader.ReadEntryStatsView()));
     }
 }
        private Post GetFirstPostWhere(StringBuilder sb, PostType postType, Func <Post, bool> func)
        {
            var  getPosts = new PostsModel(postType);
            Post testPost;

            do
            {
                var postsResp = _api.GetPosts(getPosts, CancellationToken.None)
                                .Result;

                if (!postsResp.IsSuccess)
                {
                    sb.AppendLine($"fail. Reason:{Environment.NewLine} {postsResp.Error.Message}");
                    return(null);
                }
                if (postsResp.Result.Results.Count == 0)
                {
                    sb.AppendLine("fail. Reason:{Environment.NewLine} There are no Posts!");
                    return(null);
                }

                testPost = postsResp.Result.Results.FirstOrDefault(func);
                if (testPost == null)
                {
                    getPosts.Offset = postsResp.Result.Results.Last().Url;
                }
            } while (testPost == null);
            return(testPost);
        }
Esempio n. 32
0
 public Entry(PostType postType, Blog blog)
 {
     Categories = new List<string>();
     PostConfig = PostConfig.None;
     DateModifiedUtc = NullValue.NullDateTime;
     DateCreatedUtc = NullValue.NullDateTime;
     PostType = postType;
     Blog = blog;
     Id = NullValue.NullInt32;
 }
Esempio n. 33
0
 public void Parse()
 {
     var split = Thid.Split(':');
     Thid1 = split[0];
     Thid2 = split[1];
     Type = (PostType)Int32.Parse(split[2]);
     Thid4 = split[3];
     Thid5 = split[4];
     Thid6 = split[5];
 }
 public static void GoTo(PostType postType)
 {
     switch (postType)
     {
         case PostType.Page:
             LeftNavigation.Pages.AllPages.Select();
             break;
         default:
             break;
     }
 }
Esempio n. 35
0
        public static PostList GetPostAll(string token, string keywords, PostType postType, string maxID, int pagesize=20)
        {
            var paras = new Dictionary<string, object>();
            paras.Add("access_token", token);
            paras.Add("keywords", keywords);
            paras.Add("post_type",(int) postType);
            paras.Add("max_id", maxID);
            paras.Add("pagesize", pagesize);
            var result = HttpRequest.RequestServer(ApiOption.post_v2_all, paras);

            return JsonConvert.DeserializeObject<PostList>(result);
        }
Esempio n. 36
0
 public static MvcHtmlString GetPostClassByType(this HtmlHelper helper, PostType type)
 {
     switch (type)
     {
         case PostType.SimplePost:
             return new MvcHtmlString("simple-post");
         case PostType.VideoPost:
             return new MvcHtmlString("video-post");
         default:
             throw new InvalidEnumArgumentException("Unknown post type!");
     }
 }
        public PostListViewModel(PostType postType, INavigationService navigationService, System.Action<bool> NotifyLoading)
        {
            _navigationService = navigationService;

            _ErrorMessage = "";
            _Posts = new BindableCollection<PostItem>();
            _IsLoading = false;
            NotifyLoadingAction = NotifyLoading;

            PostType = postType;
            Load();
        }
        private string MarkPostUpOrDown(Post post, Member postWriter, Member voter, PostType postType)
        {
            // Check this user is not the post owner
            if (voter.Id != postWriter.Id)
            {
                // Not the same person, now check they haven't voted on this post before
                if (post.Votes.All(x => x.MemberId != CurrentMember.Id))
                {

                    // Points to add or subtract to a user
                    var usersPoints = (postType == PostType.Negative) ?
                                        (-Settings.PointsDeductedForNegativeVote) : (Settings.PointsAddedForPositiveVote);

                    // Update the users points who wrote the post
                    ServiceFactory.MemberPointsService.Add(new MemberPoints
                    {
                        Points = usersPoints, 
                        Member = postWriter, 
                        MemberId = postWriter.Id,
                        RelatedPostId = post.Id
                    });

                    // Update the post with the new vote of the voter
                    var vote = new Vote
                    {
                        Post = post,
                        Member = voter,
                        MemberId = voter.Id,
                        Amount = (postType == PostType.Negative) ? (-1) : (1),
                        VotedByMember = CurrentMember,
                        DateVoted = DateTime.Now
                    };
                    ServiceFactory.VoteService.Add(vote);

                    // Update the post with the new points amount
                    var allVotes = post.Votes.ToList();
                    var allVoteCount = allVotes.Sum(x => x.Amount);
                    //var newPointTotal = (postType == PostType.Negative) ? (post.VoteCount - 1) : (post.VoteCount + 1);
                    post.VoteCount = allVoteCount;
                    var postTypeVoteCount = 0;
                    if (postType == PostType.Positive)
                    {
                        postTypeVoteCount = allVotes.Count(x => x.Amount > 0);
                    }
                    else
                    {
                        postTypeVoteCount =  allVotes.Count(x => x.Amount < 0);   
                    }
                    return string.Concat(postTypeVoteCount, ",", allVoteCount);
                }
            }
            return "0";
        }
        public static void GoTo(PostType postType)
        {
            switch (postType)
            {
                case PostType.Page:
                    //Refactor:
                    LeftNavigation.Pages.AllPages.Select();
                    break;

                case PostType.Posts:
                    LeftNavigation.Posts.AllPosts.Select();
                    break;
            }
        }
Esempio n. 40
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DraftPost"/> class.
        /// </summary>
        /// <param name="post">
        /// The post.
        /// </param>
        public DraftPost(Post post)
        {
            this._fileID = post.FileID;
            this._type = PostType.Draft;

            this._catID = post.CatID;
            this._oldCatID = this._catID;

            this._title = post.Title;
            this._author = post.Author;
            this._time = post.Time;

            this._comments = post.Comments;
            this._docs = post.Documents;
            this._contents = post.Contents;
        }
Esempio n. 41
0
        public void Send(string tags, PostType type, bool receivecopy)
        {
            using (MailMessage msg = new MailMessage())
            {
                foreach (KeyValuePair<string, Stream> attachment in m_attachments)
                {
                    msg.Attachments.Add(new Attachment(attachment.Value, attachment.Key));
                    m_html = m_html.Replace(attachment.Key, "cid:" + attachment.Key);
                }

                msg.From = new MailAddress(m_senderemail, "gdocerous");
                msg.ReplyToList.Add(new MailAddress(m_email));

                if (type == PostType.Private)
                    msg.To.Add(new MailAddress("*****@*****.**"));
                else if (type == PostType.Draft)
                    msg.To.Add(new MailAddress("*****@*****.**"));
                else if (type == PostType.Public)
                    msg.To.Add(new MailAddress("*****@*****.**"));

                if (receivecopy)
                    msg.Bcc.Add(new MailAddress(m_email));

                msg.Subject = string.Format("{0} ((tag: {1}))", m_documenttitle, tags);

                AlternateView htmlView = AlternateView.CreateAlternateViewFromString(m_html, new System.Net.Mime.ContentType("text/html"));

                foreach (KeyValuePair<string, Stream> attachment in m_attachments)
                {
                    LinkedResource linkedRes = new LinkedResource(attachment.Value, GetMediaType(attachment.Key));
                    linkedRes.ContentId = attachment.Key;
                    htmlView.LinkedResources.Add(linkedRes);
                }

                msg.AlternateViews.Add(htmlView);

                using (var smtp = new SmtpClient())
                {
                    smtp.Send(msg);
                }
            }
        }
Esempio n. 42
0
        public static string Update(string token, string msg, string gID, PostShareType shareType, PostType postType, out int errorCode)
        {
            errorCode = 0;
            var paras = new Dictionary<string, object>();
            paras.Add("access_token", token);
            paras.Add("p_msg", msg);
            paras.Add("g_id", gID);
            paras.Add("s_type", (int)shareType);
            paras.Add("p_type", (int)postType);
            var result = HttpRequest.RequestServer(ApiOption.post_update, paras);

            JObject resultObj =(JObject) JsonConvert.DeserializeObject(result);
            if (resultObj != null)
            {
                if (resultObj.Property("error_code") == null)
                    return resultObj["post"].ToString();
                else
                    errorCode =int.Parse( resultObj["error_code"].ToString());
            }

            return string.Empty;
            
        }
Esempio n. 43
0
 private static void ValidateEntryTypeIsNotNone(PostType entryType)
 {
     Debug.Assert(entryType != PostType.None, "The entry type is none. This should be impossible!");
 }
		public async Task<Tuple<List<RedditPost>, string, string>> LoadPostsAsync(string suffix, PostSort sort, PostType type, int countViewed, string after)
		{
			var posts = new Tuple<List<RedditPost>, string, string>(new List<RedditPost>(), "", "");

			switch (type)
			{
				case PostType.All:
					switch (sort)
					{
						case PostSort.Controversial:
							posts = await Helpers.Posts.FindControversialPostsAsync(suffix, countViewed, after);
							break;

						case PostSort.Hot:
							posts = await Helpers.Posts.FindHotPostsAsync(suffix, countViewed, after);
							break;

						case PostSort.New:
							posts = await Helpers.Posts.FindNewPostsAsync(suffix, countViewed, after);
							break;

						case PostSort.Rising:
							posts = await Helpers.Posts.FindRisingPostsAsync(suffix, countViewed, after);
							break;

						case PostSort.Top:
						default:
							posts = await Helpers.Posts.FindTopPostsAsync(suffix, countViewed, after);
							break;
					}
					break;

				case PostType.Pics:
					switch (sort)
					{
						case PostSort.Controversial:
							posts = await Helpers.Pics.FindControversialPicsAsync(suffix, countViewed, after);
							break;

						case PostSort.Hot:
							posts = await Helpers.Pics.FindHotPicsAsync(suffix, countViewed, after);
							break;

						case PostSort.New:
							posts = await Helpers.Pics.FindNewPicsAsync(suffix, countViewed, after);
							break;

						case PostSort.Rising:
							posts = await Helpers.Pics.FindRisingPicsAsync(suffix, countViewed, after);
							break;

						case PostSort.Top:
						default:
							posts = await Helpers.Pics.FindTopPicsAsync(suffix, countViewed, after);
							break;
					}
					break;

				case PostType.SelfText:
					switch (sort)
					{
						case PostSort.Controversial:
							posts = await Helpers.SelfText.FindControversialSelfTextAsync(suffix, countViewed, after);
							break;

						case PostSort.Hot:
							posts = await Helpers.SelfText.FindHotSelfTextAsync(suffix, countViewed, after);
							break;

						case PostSort.New:
							posts = await Helpers.SelfText.FindNewSelfTextAsync(suffix, countViewed, after);
							break;

						case PostSort.Rising:
							posts = await Helpers.SelfText.FindRisingSelfTextAsync(suffix, countViewed, after);
							break;

						case PostSort.Top:
						default:
							posts = await Helpers.SelfText.FindTopSelfTextAsync(suffix, countViewed, after);
							break;
					}
					break;
			}

			return posts;
		}
Esempio n. 45
0
        private string PostContent(string username, string password, ref Post post, bool publish, PostType postType)
        {
            Framework.BlogInfo info = Config.CurrentBlog;
            ValidateUser(username, password, info.AllowServiceAccess);

            Entry entry = new Entry(postType);
            entry.Author = info.Author;
            entry.Email = info.Email;
            entry.Body = post.description;
            entry.Title = post.title;
            entry.Description = string.Empty;

            //TODO: Figure out why this is here.
            //		Probably means the poster forgot to set the date.

            DateTime dateTimeInPost = Config.CurrentBlog.TimeZone.ToLocalTime(post.dateCreated);
            var lastEntryDate = DbProvider.Instance().GetLatestEntryDate();

            if (dateTimeInPost.Year >= 2003)
            {
                // this is an indication that we want to move the rest of the posts
                if (dateTimeInPost.AddHours(-1) <= Config.CurrentBlog.TimeZone.Now)
                {
                    DbProvider.Instance().PushOtherPostsDatesAfter(dateTimeInPost);
                }
                entry.DateCreated = dateTimeInPost;
                entry.DateModified = dateTimeInPost;
            }
            else
            {

                if (lastEntryDate == null) // there is no next entry date
                {
                    entry.DateCreated = Config.CurrentBlog.TimeZone.Now;
                }
                else if (lastEntryDate.Value.AddDays(1) < Config.CurrentBlog.TimeZone.Now) // the latest date it too far in the past
                {
                    entry.DateCreated = Config.CurrentBlog.TimeZone.Now;
                }
                else
                {
                    // noon the next day
                    entry.DateCreated = lastEntryDate.Value.Date.AddDays(1).AddHours(12);
                    entry.Body = "<blockquote>Originally posted at " + Config.CurrentBlog.TimeZone.Now.ToShortDateString() +
                        "</blockquote>" + entry.Body;
                }
                entry.DateModified = entry.DateCreated;
            }

            if (post.categories != null)
            {
                entry.Categories.AddRange(post.categories);
            }

            if (!string.IsNullOrEmpty(post.wp_slug))
            {
                entry.EntryName = post.wp_slug;
            }

            entry.PostType = postType;

            entry.IsActive = publish;
            if (publish)
            {
                entry.DateSyndicated = entry.DateCreated;
            }
            entry.AllowComments = true;
            entry.DisplayOnHomePage = true;
            entry.IncludeInMainSyndication = true;
            entry.IsAggregated = true;
            entry.SyndicateDescriptionOnly = false;

            int postID;
            try
            {
                postID = Entries.Create(entry);

                if (!string.IsNullOrEmpty(post.enclosure.url))
                {
                    Components.Enclosure enc = new Components.Enclosure();
                    enc.Url = post.enclosure.url;
                    enc.MimeType = post.enclosure.type;
                    enc.Size = post.enclosure.length;
                    enc.EntryId = postID;
                    Enclosures.Create(enc);
                }

                AddCommunityCredits(entry);
            }
            catch (Exception e)
            {
                throw new XmlRpcFaultException(0, e.Message + " " + e.StackTrace);
            }
            if (postID < 0)
            {
                throw new XmlRpcFaultException(0, "The post could not be added");
            }
            return postID.ToString(CultureInfo.InvariantCulture);
        }
Esempio n. 46
0
 /// <summary>
 /// Returns a pageable collection of entries ordered by the id descending.
 /// This is used in the admin section.
 /// </summary>
 /// <param name="postType">Type of the post.</param>
 /// <param name="categoryId">The category ID.</param>
 /// <param name="pageIndex">Index of the page.</param>
 /// <param name="pageSize">Size of the page.</param>
 /// <returns></returns>
 public abstract IPagedCollection<EntryStatsView> GetEntries(PostType postType, int? categoryId, int pageIndex, int pageSize);
Esempio n. 47
0
        private string PostContent(string username, string password, ref Post post, bool publish, PostType postType)
        {
            ValidateUser(username, password, Blog.AllowServiceAccess);

            var entry = new Entry(postType) {PostType = postType, IsActive = publish, Author = Blog.Author, Email = Blog.Email};
            post.CopyValuesTo(entry);
            entry.AllowComments = true;
            entry.DisplayOnHomePage = true;

            DateTime dateTimeInPost = post.dateCreated != null ? post.dateCreated.Value : DateTime.UtcNow;
            // Store in the blog's timezone
            dateTimeInPost = Blog.TimeZone.FromUtc(dateTimeInPost);

            entry.DateCreated = entry.DateModified = Blog.TimeZone.Now;
            if(publish)
            {
                entry.DateSyndicated = dateTimeInPost;
            }

            entry.IncludeInMainSyndication = true;
            entry.IsAggregated = true;
            entry.SyndicateDescriptionOnly = false;

            int postId;
            try
            {
                //TODO: Review whether keywords should be true.
                postId = EntryPublisher.Publish(entry);
                if(Blog.TrackbacksEnabled)
                {
                    NotificationServices.Run(entry, Blog, Url);
                }

                if(post.enclosure != null)
                {
                    Components.Enclosure enclosure = post.enclosure.Value.CopyValuesToEnclosure();
                    enclosure.EntryId = postId;
                    Repository.Create(enclosure);
                }

                AddCommunityCredits(entry);
            }
            catch(Exception e)
            {
                throw new XmlRpcFaultException(0, e.Message + " " + e.StackTrace);
            }
            if(postId < 0)
            {
                throw new XmlRpcFaultException(0, Resources.XmlRpcFault_AddPostFailed);
            }
            return postId.ToString(CultureInfo.InvariantCulture);
        }
Esempio n. 48
0
        public static string FormatPostText(string rawPostBody, PostType postType, bool allowCustomTransforms)
        {
            string formattedPost = rawPostBody;

            // because of the way we receive the post from MSHTML, somethings can already be encoded. This breaks the regex patterns
            // so we're unencoding anything that is already encoded so regex patterns work correctly. Later we'll encode everything again.

            //SCOTTW: Why? Encoded markup should stay encoded...otherwise it will not render
            //formattedPost = HttpUtility.HtmlDecode( formattedPost );

            if (allowCustomTransforms ) {
                // must do emoteicons first because they are restricted from finding any inside [code][/code] blocks. We have to do
                // this before the later steps remove the [code][/code] blocks.
                if( CSContext.Current.SiteSettings.EnableEmoticons ) {
                    formattedPost = EmoticonTransforms(formattedPost);
                }
            }

            // convert any html inside code/pre blocks into encoded html
            formattedPost = EncodeCodeBlocks( formattedPost );

            // strip the html posts of any offending html tags and encode any that don't meet the criteria.
            formattedPost = HtmlScrubber.Clean(formattedPost,false,true);//  ScrubHtml( formattedPost, postType );

            // convert all html tags to bbcode as the bbcode processor will only allow safe attributes to be included in the ponst.
            //			formattedPost = HtmlToBBCode( formattedPost );

            // Remove any script code
            //
            //			formattedPost = Transforms.StripScriptTags(formattedPost);

            // Peform specialized transforms first.
            //

            // Do BBCode transform, if any
            //
            formattedPost = BBcodeToHtml(formattedPost);

            // Perform HTML Encoding of any tag elements, if not PostType.HTML
            //
            if (postType != PostType.HTML && postType != PostType.Poll) {
                formattedPost = HttpUtility.HtmlEncode(formattedPost);
                formattedPost = formattedPost.Replace("\n", Globals.HtmlNewLine);

                // Fix to reverse certain items that were HtmlEncoded above
                //
                formattedPost = UnHtmlEncode(formattedPost);
            }

            return formattedPost;
        }
Esempio n. 49
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="encodedString"></param>
        /// <param name="postType"></param>
        /// <returns></returns>
        static string ScrubHtml( string encodedString, PostType postType )
        {
            System.Collections.Hashtable ht = GetAllowedTags();

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            encodedString = Regex.Replace(encodedString, @"(<!--)", @"&lt;!--", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace );
            encodedString = Regex.Replace(encodedString, @"(-->)", @"--&gt;", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace );
            //			string[] blocks = Regex.Split(encodedString, @"((<(?:\/)?\w+(?:\s+\w+(?:\s*=\s*""?\w+""?)?)*\s*(?:\/)?>)|(<\!--)|(-->))", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace );
            // string[] blocks = Regex.Split(encodedString, @"\b(<(?:\/)?\w+(?:\s+\w+(?:\s*=\s*""?(?:[\w-_:#\'\s%]*|(?:(?:http|ftp|https):\/\/)?[\w-_]+(?:\.[\w-_]+)+(?:[\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)""?)?)*\s*(?:\/)?>)", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace );
            //			string[] blocks = Regex.Split(encodedString, @"(<(?:\/)?\w+\s*(?:\w+)*\s*(?:\/)?>)", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace );
            string[] blocks = Regex.Split(encodedString, @"\b<(\/?\w*)(\s*(\w*)(?:\s*=\s*(?:""[^""]*""|'[^']'|[^>]*))?)*\/?>\b", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace );
            string output = "";
            int keyStart = 1;

            foreach( string block in blocks ) {
                output = block;
                if( output.StartsWith("<") ) {
                    if( output[1] == '/' )
                        keyStart = 2;
                    else
                        keyStart = 1;

                    int keyEnd = output.IndexOfAny(new char[]{' ', '/', '>'}, keyStart) - keyStart;
                    string key = output.Substring(keyStart, keyEnd).ToLower();
                    StringBuilder sbAttr = new StringBuilder();
                    if( ht.ContainsKey( key )) {
                        string slashClosing = output.EndsWith("/>") ? "/" : "";
                        string slashOpening = output.StartsWith("</") ? "/" : "";
                        string attributes	= (string)ht[key];
                        if( attributes != null && attributes.Length > 0 ) {
                            string[] allowedAttr = ((string)ht[key]).Split(',');
                            //foreach( Match match in Regex.Matches(output, String.Format(@"<{0}((?:\s+(\w+)(?:\s*=""?\w+""?)?)*)?\s*[\/\?]?>", key), RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace )) {
                            //foreach( Match match in Regex.Matches(output, String.Format(@"<{0}((?:\s+(\w+)(?:\s*=\s*""?(?:\w*|(?:(?:http|ftp|https):\/\/)?[\w-_]+(?:\.[\w-_]+)+(?:[\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)""?)?)*)\s*[\/\?]?>", key), RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace )) {
                            string attrPattern = String.Format(@"<{0}(\s*(\w*)(?:\s*=\s*(?:""[^""]*""|'[^']'|[^>]*))?)*\/?>", key);
                            MatchCollection matches = Regex.Matches(output, attrPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace );
                            foreach( Match match in matches ) {
                                foreach( string attr in allowedAttr ) {
                                    if( match.Groups[2].Captures[0].Value == attr ) {
                                        sbAttr.Append( match.Groups[1].Captures[0].Value );
                                    }
                                }
                            }
                        }

                        sb.AppendFormat("<{0}{1}{2}{3}>", slashOpening, key, sbAttr.ToString(), slashClosing );//Regex.Replace( output, (string)ht[key], "<$1 $2>$3</$1>", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace ) );
                    }
                    else {
                        sb.Append( HttpUtility.HtmlEncode( output ) );
                    }
                }
                else {
                    sb.Append( output );
                }
            }

            return sb.ToString();
        }
Esempio n. 50
0
        /*
        public void GetBlogQueue(string blogHostName)
        {
            if (String.IsNullOrEmpty(blogHostName))
                throw new ArgumentException("invalid blog host name");

            var client = GetRestClient();

            var resource = string.Format("/blog/{0}/posts/queue", blogHostName);

            var request = new RestRequest(resource, Method.GET);

            var response = client.Execute(request);

            Console.WriteLine(response.StatusCode);
        }*/
        //TODO: Write some overloads for this
        public List<TumblrPost> GetBlogPosts(string blogHostName, PostFormat format = PostFormat.Html, string filteredTag = "", bool includeReblogs = false, bool includeNotes = false, int offset = 0, int limit = 20, PostType postType = PostType.All )
        {
            if (String.IsNullOrEmpty(blogHostName))
                throw new ArgumentException("invalid blog host name");

            var client = GetUnAuthenticatedRestClient();

            string typeUrl = "";

            switch (postType)
            {
                    case PostType.Text:
                        typeUrl = "/text";
                        break;
                    case PostType.Quote:
                        typeUrl = "/quote";
                        break;
                    case PostType.Link:
                        typeUrl = "/link";
                        break;
                    case PostType.Audio:
                        typeUrl = "/audio";
                        break;
                    case PostType.Video:
                        typeUrl = "/video";
                        break;
                    case PostType.Answer:
                        typeUrl = "/answer";
                        break;
                    case PostType.Photo:
                        typeUrl = "/photo";
                        break;
                    default:
                        typeUrl = "";
                        break;

            }

            //post type on end of url for this one
            var resource = string.Format("/blog/{0}/posts{1}", blogHostName, typeUrl);

            var request = new RestRequest(resource);

            request.AddParameter(new Parameter() { Name = "api_key", Type = ParameterType.GetOrPost, Value = ConsumerKey });
            request.AddParameter("limit", limit);
            request.AddParameter("offset", offset);

            if(filteredTag != "")
                request.AddParameter("tag", filteredTag);

            request.AddParameter("reblog_info", includeReblogs);
            request.AddParameter("notes_info", includeNotes);

            var response = client.Execute<TumblrResponse<TumblrPostsResponse>>(request);

            return ConvertPosts(response.Data.Response.Posts);
        }
Esempio n. 51
0
 /// <summary>
 /// Gets the entries that meet the <see cref="PostType"/> and 
 /// <see cref="PostConfig"/> flags.
 /// </summary>
 /// <param name="itemCount">Item count.</param>
 /// <param name="postType">The type of entry to return.</param>
 /// <param name="postConfig">Post Configuration options.</param>
 /// <param name="includeCategories">Whether or not to include categories</param>
 /// <returns></returns>
 public abstract ICollection<Entry> GetEntries(int itemCount, PostType postType, PostConfig postConfig, bool includeCategories);
Esempio n. 52
0
 public abstract ICollection<Entry> GetPostsByDayRange(DateTime start, DateTime stop, PostType postType, bool activeOnly);
		public async Task<bool> LoadMorePostsAsync(string suffix, PostSort sort, PostType type)
		{
			Tuple<List<RedditPost>, string, string> posts = await LoadPostsAsync(suffix, sort, type, CountViewed, AfterPost);

			foreach (RedditPost p in posts.Item1)
			{
				Posts.Add(p);
			}
			BeforePost = posts.Item2;
			AfterPost = posts.Item3;
			await CheckPostStuff();

			CountViewed += 25;

			_loading = false;

			return true;
		}
Esempio n. 54
0
 /// <summary>
 /// Returns the previous and next entry to the specified entry.
 /// </summary>
 /// <param name="entryId"></param>
 /// <param name="postType"></param>
 /// <returns></returns>
 public abstract ICollection<EntrySummary> GetPreviousAndNextEntries(int entryId, PostType postType);
Esempio n. 55
0
		/// <summary>
		/// Asynchronously retrieves posts from the current user's dashboard.
		/// </summary>
		/// See:  http://www.tumblr.com/docs/en/api/v2#m-ug-dashboard
		/// <param name="sinceId">
		///  Return posts that have appeared after the specified ID. Use this parameter to page through the results: first get a set 
		///  of posts, and then get posts since the last ID of the previous set.  
		/// </param>
		/// <param name="startIndex">
		/// The post number to start at.
		/// </param>
		/// <param name="count">
		/// The number of posts to return.
		/// </param>
		/// <param name="type">
		/// The <see cref="PostType"/> to return.
		/// </param>
		/// <param name="includeReblogInfo">
		/// Whether or not the response should include reblog info.
		/// </param>
		/// <param name="includeNotesInfo">
		/// Whether or not the response should include notes info.
		/// </param>
		/// <returns>
		/// A <see cref="Task{T}"/> that can be used to track the operation. If the task succeeds, the <see cref="Task{T}.Result"/> will
		/// carry an array of posts. Otherwise <see cref="Task.Exception"/> will carry a <see cref="TumblrException"/>
		/// representing the error occurred during the call.
		/// </returns>
		/// <exception cref="ObjectDisposedException">
		/// The object has been disposed.
		/// </exception>
		/// <exception cref="InvalidOperationException">
		/// This <see cref="TumblrClient"/> instance does not have an OAuth token specified.
		/// </exception>
		/// <exception cref="ArgumentOutOfRangeException">
		/// <list type="bullet">
		/// <item>
		///		<description>
		///			<paramref name="sinceId"/> is less than 0.
		///		</description>
		///	</item>
		/// <item>
		///		<description>
		///			<paramref name="startIndex"/> is less than 0.
		///		</description>
		///	</item>
		///	<item>
		///		<description>
		///			<paramref name="count"/> is less than 1 or greater than 20.
		///		</description>
		///	</item>
		/// </list>
		/// </exception>
		public Task<BasePost[]> GetDashboardPostsAsync(long sinceId = 0, long startIndex = 0, int count = 20, PostType type = PostType.All, bool includeReblogInfo = false, bool includeNotesInfo = false)
		{
			if (disposed)
				throw new ObjectDisposedException("TumblrClient");

			if (sinceId < 0)
				throw new ArgumentOutOfRangeException("sinceId", "sinceId must be greater or equal to zero.");

			if (startIndex < 0)
				throw new ArgumentOutOfRangeException("startIndex", "startIndex must be greater or equal to zero.");

			if (count < 1 || count > 20)
				throw new ArgumentOutOfRangeException("count", "count must be between 1 and 20.");

			if (OAuthToken == null)
				throw new InvalidOperationException("GetDashboardPostsAsync method requires an OAuth token to be specified.");

			MethodParameterSet parameters = new MethodParameterSet();
			parameters.Add("type", type.ToString().ToLowerInvariant(), "all");
			parameters.Add("since_id", sinceId, 0);
			parameters.Add("offset", startIndex, 0);
			parameters.Add("limit", count, 0);
			parameters.Add("reblog_info", includeReblogInfo, false);
			parameters.Add("notes_info", includeNotesInfo, false);

			return CallApiMethodAsync<PostCollection, BasePost[]>(
				new UserMethod("dashboard", OAuthToken, HttpMethod.Get, parameters),
				r => r.Posts,
				CancellationToken.None);
		}
Esempio n. 56
0
 public static string FormatPostText(string rawPostBody, PostType postType)
 {
     return FormatPostText (rawPostBody, postType, true);
 }
Esempio n. 57
0
 public Entry(PostType postType)
     : this(postType, Config.CurrentBlog)
 {
 }
Esempio n. 58
0
		/// <summary>
		/// Asynchronously retrieves published posts from a blog.
		/// </summary>
		/// <remarks>
		/// See: http://www.tumblr.com/docs/en/api/v2#posts
		/// </remarks>
		/// <param name="blogName">
		/// The name of the blog.
		/// </param>
		/// <param name="startIndex">
		/// The offset at which to start retrieving the posts. Use 0 to start retrieving from the latest post.
		/// </param>
		/// <param name="count">
		/// The number of posts to retrieve. Must be between 1 and 20.
		/// </param>
		/// <param name="type">
		/// The <see cref="PostType"/> to retrieve.
		/// </param>
		/// <param name="includeReblogInfo">
		/// Whether or not to include reblog info with the posts.
		/// </param>
		/// <param name="includeNotesInfo">
		/// Whether or not to include notes info with the posts.
		/// </param>
		/// <param name="filter">
		/// A <see cref="PostFilter"/> to apply.
		/// </param>
		/// <param name="tag">
		/// A tag to filter by.
		/// </param>
		/// <returns>
		/// A <see cref="Task{T}"/> that can be used to track the operation. If the task succeeds, the <see cref="Task{T}.Result"/> will
		/// carry a <see cref="Posts"/> instance. Otherwise <see cref="Task.Exception"/> will carry a <see cref="TumblrException"/>
		/// representing the error occurred during the call.
		/// </returns>
		/// <exception cref="ObjectDisposedException">
		/// The object has been disposed.
		/// </exception>
		/// <exception cref="ArgumentNullException">
		/// <paramref name="blogName"/> is <b>null</b>.
		/// </exception>
		/// <exception cref="ArgumentException">
		/// <paramref name="blogName"/> is empty.
		/// </exception>
		/// <exception cref="ArgumentOutOfRangeException">
		/// <list type="bullet">
		/// <item>
		///		<description>
		///			<paramref name="startIndex"/> is less than 0.
		///		</description>
		///	</item>
		///	<item>
		///		<description>
		///			<paramref name="count"/> is less than 1 or greater than 20.
		///		</description>
		///	</item>
		/// </list>
		/// </exception>
		public Task<Posts> GetPostsAsync(string blogName, long startIndex = 0, int count = 20, PostType type = PostType.All, bool includeReblogInfo = false, bool includeNotesInfo = false, PostFilter filter = PostFilter.Html, string tag = null)
		{
			if (disposed)
				throw new ObjectDisposedException("TumblrClient");

			if (blogName == null)
				throw new ArgumentNullException("blogName");

			if (blogName.Length == 0)
				throw new ArgumentException("Blog name cannot be empty.", "blogName");

			if (startIndex < 0)
				throw new ArgumentOutOfRangeException("startIndex", "startIndex must be greater or equal to zero.");

			if (count < 1 || count > 20)
				throw new ArgumentOutOfRangeException("count", "count must be between 1 and 20.");

			string methodName = null;
			switch (type)
			{
				case PostType.Text: methodName = "posts/text"; break;
				case PostType.Quote: methodName = "posts/quote"; break;
				case PostType.Link: methodName = "posts/link"; break;
				case PostType.Answer: methodName = "posts/answer"; break;
				case PostType.Video: methodName = "posts/video"; break;
				case PostType.Audio: methodName = "posts/audio"; break;
				case PostType.Photo: methodName = "posts/photo"; break;
				case PostType.Chat: methodName = "posts/chat"; break;
				case PostType.All:
				default: methodName = "posts"; break;
			}

			MethodParameterSet parameters = new MethodParameterSet();
			parameters.Add("api_key", apiKey);
			parameters.Add("offset", startIndex, 0);
			parameters.Add("limit", count, 0);
			parameters.Add("reblog_info", includeReblogInfo, false);
			parameters.Add("notes_info", includeNotesInfo, false);
			parameters.Add("filter", filter.ToString().ToLowerInvariant(), "html");
			parameters.Add("tag", tag);

			return CallApiMethodAsync<Posts>(
				new BlogMethod(blogName, methodName, null, HttpMethod.Get, parameters),
				CancellationToken.None);
		}
Esempio n. 59
0
 protected override object this[string index]
 {
     get
     {
         #region
         switch (index)
         {
             case "GuildID": return GuildID;
             case "UserID": return UserID;
             case "PostType": return PostType;
             case "Contribution": return Contribution;
             case "TotalContribution": return TotalContribution;
             case "IncenseNum": return IncenseNum;
             case "IncenseDate": return IncenseDate;
             case "DevilNum": return DevilNum;
             case "SummonNum": return SummonNum;
             case "IsDevil": return IsDevil;
             case "DevilDate": return DevilDate;
             case "InsertDate": return InsertDate;
             case "GainBlessing": return GainBlessing;
             case "CurrNum": return CurrNum;
             case "RefreshDate": return RefreshDate;
             case "DonateCoin": return DonateCoin;
             case "DonateGold": return DonateGold;
             case "TotalDonate": return TotalDonate;
             default: throw new ArgumentException(string.Format("GuildMember index[{0}] isn't exist.", index));
         }
         #endregion
     }
     set
     {
         #region
         switch (index)
         {
             case "GuildID":
                 _GuildID = value.ToNotNullString();
                 break;
             case "UserID":
                 _UserID = value.ToNotNullString();
                 break;
             case "PostType":
                 _PostType = value.ToEnum<PostType>();
                 break;
             case "Contribution":
                 _Contribution = value.ToInt();
                 break;
             case "TotalContribution":
                 _TotalContribution = value.ToInt();
                 break;
             case "IncenseNum":
                 _IncenseNum = value.ToInt();
                 break;
             case "IncenseDate":
                 _IncenseDate = value.ToDateTime();
                 break;
             case "DevilNum":
                 _DevilNum = value.ToInt();
                 break;
             case "SummonNum":
                 _SummonNum = value.ToInt();
                 break;
             case "IsDevil":
                 _IsDevil = value.ToInt();
                 break;
             case "DevilDate":
                 _DevilDate = value.ToDateTime();
                 break;
             case "InsertDate":
                 _InsertDate = value.ToDateTime();
                 break;
             case "GainBlessing":
                 _GainBlessing = value.ToInt();
                 break;
             case "CurrNum":
                 _CurrNum = value.ToInt();
                 break;
             case "RefreshDate":
                 _RefreshDate = value.ToDateTime();
                 break;
             case "DonateCoin":
                 _DonateCoin = value.ToInt();
                 break;
             case "DonateGold":
                 _DonateGold = value.ToInt();
                 break;
             case "TotalDonate":
                 _TotalDonate = value.ToInt();
                 break;
             default: throw new ArgumentException(string.Format("GuildMember index[{0}] isn't exist.", index));
         }
         #endregion
     }
 }
Esempio n. 60
0
        private void MarkPostUpOrDown(Post post, MembershipUser postWriter, MembershipUser voter, PostType postType)
        {
            // Check this user is not the post owner
            if (voter.Id != postWriter.Id)
            {
                // Not the same person, now check they haven't voted on this post before
                if (post.Votes.All(x => x.User.Id != LoggedOnUser.Id))
                {

                    // Points to add or subtract to a user
                    var usersPoints = (postType == PostType.Negative) ?
                                        (-SettingsService.GetSettings().PointsDeductedNagativeVote) : (SettingsService.GetSettings().PointsAddedPostiveVote);

                    // Update the users points who wrote the post
                    _membershipUserPointsService.Add(new MembershipUserPoints { Points = usersPoints, User = postWriter });

                    // Update the post with the new vote of the voter
                    var vote = new Vote
                    {
                        Post = post,
                        User = voter,
                        Amount = (postType == PostType.Negative) ? (-1) : (1),
                        VotedByMembershipUser = LoggedOnUser,
                        DateVoted = DateTime.UtcNow
                    };
                    _voteService.Add(vote);

                    // Update the post with the new points amount
                    var newPointTotal = (postType == PostType.Negative) ? (post.VoteCount - 1) : (post.VoteCount + 1);
                    post.VoteCount = newPointTotal;
                }
            }
        }