Пример #1
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)));
        }
Пример #2
0
        public static void AssertCanPostTypeToOrganization(PostType postType, Organization org,
                                                           OrganizationMember orgMember, AuthUserSession user)
        {
            if (user.IsOrganizationModerator(orgMember))
            {
                if (!org.ModeratorPostTypes.IsEmpty())
                {
                    if (!org.ModeratorPostTypes.Contains(postType.ToString()))
                    {
                        throw HttpError.Forbidden(postType + " is not an allowed Type for Moderators");
                    }
                    return;
                }
            }

            if (!org.PostTypes.IsEmpty())
            {
                if (!org.PostTypes.Contains(postType.ToString()))
                {
                    throw HttpError.Forbidden($"You cannot submit {postType} posts here");
                }
            }
        }
Пример #3
0
        protected override string BuildPostContentString()
        {
            string result;

            // PostThumbnails can not be an empty string when creating new posts. If a featured image wasn't chosen,
            // don't use the featured image version of the content payload.
            if (PostType == ePostType.post && Post.PostThumbnail != null && Post.PostThumbnail.Length > 0 && DataService.Current.CurrentBlog.SupportsFeaturedImage())
            {
                _content = XMLRPCTable.metaWeblog_newPost_featuredImage;
                result   = string.Format(_content,
                                         Post.PostId != null ?  Post.PostId : "",
                                         Credentials.UserName != null ? Credentials.UserName.HtmlEncode() : "",
                                         Credentials.Password != null ? Credentials.Password.HtmlEncode() : "",
                                         Post.MtKeyWords != null ? Post.MtKeyWords.XmlEscape() : "",
                                         PostType.ToString(),
                                         FormatCategories(),
                                         Post.Title != null ? Post.Title.XmlEscape() : "",
                                         Post.Description != null ? Post.Description.HtmlEncode() : "",
                                         PostType.ToString(),
                                         Post.PostStatus != null ? Post.PostStatus : "",
                                         FormatCustomFields(),
                                         Post.PostFormat != null ? Post.PostFormat : "",
                                         Post.PostThumbnail != null ? Post.PostThumbnail : "",
                                         String.Format(XmlRPCRequestConstants.DATETIMEFORMATSTRING, Post.DateCreatedGMT)
                                         );
            }
            else
            {
                result = string.Format(_content,
                                       Post.PostId != null ? Post.PostId : "",
                                       Credentials.UserName != null ? Credentials.UserName.HtmlEncode() : "",
                                       Credentials.Password != null ? Credentials.Password.HtmlEncode() : "",
                                       Post.MtKeyWords != null ? Post.MtKeyWords.XmlEscape() : "",
                                       PostType.ToString(),
                                       FormatCategories(),
                                       Post.Title != null ? Post.Title.XmlEscape() : "",
                                       Post.Description != null ? Post.Description.HtmlEncode() : "",
                                       PostType.ToString(),
                                       Post.PostStatus != null ? Post.PostStatus : "",
                                       FormatCustomFields(),
                                       Post.PostFormat != null ? Post.PostFormat : "",
                                       String.Format(XmlRPCRequestConstants.DATETIMEFORMATSTRING, Post.DateCreatedGMT)
                                       );
            }
            return(result);
        }
Пример #4
0
 public CreatePostRequest(
     string categoryId,
     string title,
     string text,
     PostType type,
     decimal price      = 0,
     bool isNsfw        = false,
     string email       = null,
     string phoneNumber = null) : base("posts")
 {
     this.Post()
     .Parameter(nameof(categoryId), categoryId)
     .Parameter(nameof(title), title)
     .Parameter(nameof(text), text)
     .Parameter(nameof(type), type.ToString())
     .Parameter(nameof(price), price.ToString())
     .Parameter(nameof(isNsfw), isNsfw.ToString())
     .Parameter(nameof(email), email)
     .Parameter(nameof(phoneNumber), phoneNumber);
 }
Пример #5
0
        protected override string BuildPostContentString()
        {
            string result;

            if (DataService.Current.CurrentBlog.SupportsFeaturedImage() && PostType == ePostType.post)
            {
                _content = XMLRPCTable.metaWeblog_editPost_featuredImage;
                result   = string.Format(_content,
                                         Post.PostId,
                                         Credentials.UserName.HtmlEncode(),
                                         Credentials.Password.HtmlEncode(),
                                         Post.MtKeyWords.XmlEscape(),
                                         PostType.ToString(),
                                         FormatCategories(),
                                         Post.Title.XmlEscape(),
                                         Post.Description.HtmlEncode(),
                                         PostType.ToString(),
                                         Post.PostStatus,
                                         Post.PostFormat,
                                         Post.PostThumbnail,
                                         String.Format(XmlRPCRequestConstants.DATETIMEFORMATSTRING, Post.DateCreated.ToUniversalTime()));
            }
            else
            {
                result = string.Format(_content,
                                       Post.PostId,
                                       Credentials.UserName.HtmlEncode(),
                                       Credentials.Password.HtmlEncode(),
                                       Post.MtKeyWords.XmlEscape(),
                                       PostType.ToString(),
                                       FormatCategories(),
                                       Post.Title.XmlEscape(),
                                       Post.Description.HtmlEncode(),
                                       PostType.ToString(),
                                       Post.PostStatus,
                                       Post.PostFormat,
                                       String.Format(XmlRPCRequestConstants.DATETIMEFORMATSTRING, Post.DateCreated.ToUniversalTime()));
            }

            return(result);
        }
Пример #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="type">
        /// The type of post to return. Specify one of the following:  text, quote, link, answer, video, audio, photo, chat.
        /// default to none i.e all posts.
        /// </param>
        public Response <PostCollection> RequestPosts(PostType type = PostType.None, int offset = 0, int limit = 20, long?id = null, string tag = null, Filter filter = Filter.Raw, bool reblogInfo = false, bool notesInfo = false)
        {
            StringBuilder queryParameters = new StringBuilder();

            if (offset != 0)
            {
                queryParameters.AppendFormat("&offset={0}", offset);
            }
            if (limit != 20)
            {
                queryParameters.AppendFormat("&limit={0}", limit);
            }
            if (id != null)
            {
                queryParameters.AppendFormat("&id={0}", id.Value);
            }
            if (!string.IsNullOrWhiteSpace(tag))
            {
                queryParameters.AppendFormat("&tag={0}", tag);
            }
            if (reblogInfo == true)
            {
                queryParameters.AppendFormat("&reblog_info={0}", reblogInfo);
            }
            if (notesInfo == true)
            {
                queryParameters.AppendFormat("&notes_info={0}", notesInfo);
            }
            queryParameters.AppendFormat("&filter={0}", filter.ToString().ToLowerInvariant());
            string url = string.Format("{0}/posts{1}?api_key={2}{3}",
                                       FormatRequestUrl(RequestType.Blog),
                                       (type == PostType.None ? "" : "/" + type.ToString().ToLowerInvariant()),
                                       this.ApiKey,
                                       queryParameters.ToString());

            //todo: handle id, and therefore, post instead of post collection
            return(DoRequest <PostCollection>(url));
        }
Пример #7
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);
		}
Пример #8
0
        public AliExpressPostResult Post(string url)
        {
            try
            {
                HtmlNode.ElementsFlags.Remove("form");

                IWebDriver browser = Browser.Instance;
                browser.Navigate().GoToUrl(url);
                var sourceCode = browser.PageSource;
                while (sourceCode.Contains("Please input captcha"))
                {
                    Thread.Sleep(10000);
                    sourceCode = browser.PageSource;
                }

                if (sourceCode.Contains("The Best Value Online"))
                {
                    return(new AliExpressPostResult
                    {
                        SourceUrl = url,
                        Success = false,
                        Reason = "Login page"
                    });
                }

                //browser.Close();
                var doc = new HtmlDocument();
                doc.LoadHtml(sourceCode);

                //HtmlDocument doc =
                //    new HtmlWeb
                //    {
                //        UserAgent = chromeUserAgent
                //    }.Load(url);

                //WebClient webClient = new WebClient();
                //var proxy = ProxyProvider.GetRandomProxy();
                //webClient.Proxy = new WebProxy(proxy);
                //var page = webClient.DownloadString(url);

                //HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                //doc.LoadHtml(page);


                var product = new Product();
                product.in_stock = true;
                product.enable_html_description       = true;
                product.enable_html_short_description = true;

                HandleCategory(doc, product);

                var imageId = HandleImages(doc, product);
                HandleTitleAndDescription(doc, product);

                var productIdElement = doc.DocumentNode.Descendants()
                                       .FirstOrDefault(a => a.Name.Equals("input") && a.Attributes["name"] != null &&
                                                       a.Attributes["name"].Value.Equals("objectId"));

                product.sku = productIdElement.Attributes["value"].Value;

                if (ProductExists(product.sku))
                {
                    return(new AliExpressPostResult
                    {
                        SourceUrl = url,
                        Success = false,
                        Reason = "Product already exist"
                    });
                }


                HandlePrice(doc, product);

                HandleWeightAndDimension(doc, product);

                HandleVariationAndAttributes(doc, product, imageId);

                HandleShippingInformation(doc, product);

                product.status = postType.ToString().ToLower();

                var resultStr = wc.PostProduct(product).Result;
                var result    = JsonConvert.DeserializeObject <WooCommerceResult>(resultStr);

                return(new AliExpressPostResult
                {
                    PostedUrl = result.product.permalink,
                    SourceUrl = url,
                    Name = result.product.title,
                    Success = true
                });
            }
            catch (Exception ex)
            {
                return(new AliExpressPostResult
                {
                    SourceUrl = url,
                    Success = false,
                    Reason = ex.Message
                });
            }
        }
    public static WebResponse JSONPost(string uri, string parameters, string accestoken, PostType postmethod)
    {
        // parameters: name1=value1&name2=value2
            WebRequest webRequest = WebRequest.Create(uri);
            webRequest.Method = postmethod.ToString();
            if (postmethod != PostType.GET)
            {
                Stream os = null;
                try
                { // send the Post
                    //Add the Access Code and the Parameter to the String
                    Administration admin = new Administration();

                    webRequest.ContentType = "application/json";
                    webRequest.Headers.Add(HttpRequestHeader.Authorization, string.Format("Bearer {0}", accestoken));
                    webRequest.Headers.Add("X-IFORM-API-REQUEST-ENCODING", "JSON");
                    webRequest.Headers.Add("X-IFORM-API-VERSION", "5.1");
                    using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
                    {
                        streamWriter.Write(parameters);
                    }
                    WebResponse webResponse = webRequest.GetResponse();
                    return webResponse;
                }
                catch (WebException ex)
                {

                    //TODO:  Handle Exception
                    //MessageBox.Show(ex.Message, "HttpPost: Request error",
                    //   MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (os != null)
                    {
                        os.Close();
                    }
                }
            }

            return null;
    }
    /// <summary>
    /// HTTPs the post.
    /// </summary>
    /// <param name="uri">The URI.</param>
    /// <param name="parameters">The parameters.</param>
    /// <param name="postmethod">The postmethod.</param>
    /// <returns></returns>
    public static WebResponse HttpPost(string uri, string parameters,string accestoken ,PostType postmethod)
    {
        // parameters: name1=value1&name2=value2
            WebRequest webRequest = WebRequest.Create(uri);
            webRequest.Method = postmethod.ToString();
            if (postmethod != PostType.GET)
            {
                Stream os = null;
                try
                { // send the Post
                    //Add the Access Code and the Parameter to the String
                    Administration admin = new Administration();
                    string opts = "ACCESS_TOKEN=" + accestoken + "&VERSION=5.1";
                    if (parameters == null)
                        parameters = opts;
                    else
                        parameters = string.Format("{0}&{1}", opts, parameters);

                    webRequest.ContentType = "application/x-www-form-urlencoded";
                    byte[] bytes = Encoding.ASCII.GetBytes(parameters);
                    webRequest.ContentLength = bytes.Length;   //Count bytes to send
                    webRequest.Method = postmethod.ToString();

                    os = webRequest.GetRequestStream();
                    os.Write(bytes, 0, bytes.Length);         //Send it
                    WebResponse webResponse = webRequest.GetResponse();
                    return webResponse;
                }
                catch (WebException ex)
                {

                    //TODO:  Handle Exception
                    //MessageBox.Show(ex.Message, "HttpPost: Request error",
                    //   MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (os != null)
                    {
                        os.Close();
                    }
                }
            }

            return null;
    }
Пример #11
0
        /// <summary>
        /// Generic private method to be used by either overloaded method
        /// </summary>
        /// <param name="blog"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        /// <param name="type"></param>
        /// <param name="filter"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        async private static Task <BlogRoot> GetAllBaseAsync(
            string blog,
            int?offset    = null,
            int?count     = null,
            PostType type = PostType.All,
            Filter filter = Filter.None,
            long?id       = null)
        {
            if (string.IsNullOrEmpty(blog))
            {
                throw new ArgumentNullException("blog");
            }

            // build our request
            var request = blog
                          .GenerateUrl();

            // add parameters
            if (offset.HasValue)
            {
                request = request.SetQueryParam("start", offset.Value);
            }
            if (count.HasValue)
            {
                request = request.SetQueryParam("num", count.Value);
            }
            if (type != PostType.All)
            {
                request = request.SetQueryParam("type", type.ToString().ToLower());
            }
            if (filter != Filter.None)
            {
                string useFilter = "";
                switch (filter)
                {
                case Filter.Raw:
                    useFilter = "none";
                    break;

                case Filter.Text:
                    useFilter = "text";
                    break;
                }
                request = request.SetQueryParam("filter", useFilter);
            }
            if (id.HasValue)
            {
                request = request.SetQueryParam("id", id.Value);
            }

            // get our data
            var json = await request.GetStringAsync();

            // convert JSON using our custom reader
            return(await Task.Factory.StartNew(() =>
            {
                var result = JsonConvert.DeserializeObject <BlogRoot>(json.StripJS(), new PostArrayConverter());

                // make our total posts accessible in the Blog instance
                result.Blog.TotalPosts = result.TotalPosts;

                return result;
            }));
        }
Пример #12
0
 public void Add(PostType value, string text)
 {
     Add(value.ToString("d"), text);
 }
Пример #13
0
        protected virtual Document MapPost(TblPosts post, TblLanguages language, PostType?postType)
        {
            var title        = post.GetLocalized(p => p.Title, language.Id);
            var descriptions = post.Descriptions.Where(p => p.AddToSearchEngineIndexes).Aggregate("",
                                                                                                  (current, description) =>
                                                                                                  current + description.GetLocalized(p => p.HtmlDescription, language.Id)?.ConvertHtmlToText() +
                                                                                                  Environment.NewLine + Environment.NewLine);
            var tags = post.Tags.Aggregate("",
                                           (current, tag) => current + tag.GetLocalized(p => p.Tag, language.Id) + ", ");
            var categories = post.Categories.Aggregate("",
                                                       (current, cat) => current + (cat.Id + " , "));
            var keyWords = post.GetLocalized(p => p.MetaKeyWords, language.Id);

            var document = new Document();


            document.Add(new Field("ID", post.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.Add(new Field("PostType", postType?.ToString() ?? "", Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.Add(new Field("LanguageId", language.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.Add(new Field("LanguageCode", language.IsoCode, Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.Add(new Field("PublishDate", DateTools.DateToString(post.PublishDate, DateTools.Resolution.SECOND),
                                   Field.Store.YES, Field.Index.ANALYZED));
            document.Add(new Field("LastUpDate",
                                   DateTools.DateToString(post.LastUpDate ?? post.PublishDate, DateTools.Resolution.SECOND),
                                   Field.Store.YES, Field.Index.ANALYZED));
            var numberOfViewField = new NumericField("NumberOfVisit", Field.Store.YES, true);

            numberOfViewField.SetIntValue(post.NumberOfViews);
            document.Add(numberOfViewField);


            if (!string.IsNullOrEmpty(title))
            {
                var titleField = new Field("Title",
                                           title,
                                           Field.Store.YES,
                                           Field.Index.ANALYZED,
                                           Field.TermVector.WITH_POSITIONS_OFFSETS)
                {
                    Boost = 100
                };
                document.Add(titleField);
            }


            if (!string.IsNullOrWhiteSpace(descriptions.Replace(Environment.NewLine, "")))
            {
                var descriptionField = new Field("Description",
                                                 descriptions,
                                                 Field.Store.YES,
                                                 Field.Index.ANALYZED,
                                                 Field.TermVector.WITH_POSITIONS_OFFSETS)
                {
                    Boost = 50
                };
                document.Add(descriptionField);
            }


            if (!string.IsNullOrWhiteSpace(tags.Replace(", ", "")))
            {
                var tagField = new Field("Tags",
                                         tags,
                                         Field.Store.YES,
                                         Field.Index.ANALYZED,
                                         Field.TermVector.WITH_POSITIONS_OFFSETS)
                {
                    Boost = 50
                };
                document.Add(tagField);
            }


            var categoriesField = new Field("Categories",
                                            categories,
                                            Field.Store.YES,
                                            Field.Index.ANALYZED);

            document.Add(categoriesField);


            if (!string.IsNullOrEmpty(keyWords))
            {
                var keywordsField = new Field("Keywords",
                                              keyWords,
                                              Field.Store.YES,
                                              Field.Index.ANALYZED,
                                              Field.TermVector.WITH_POSITIONS_OFFSETS)
                {
                    Boost = 50
                };
                document.Add(keywordsField);
            }

            return(document);
        }