Tách các thẻ img bằng HTML Agility Pack

string html;
using (WebClient client = new WebClient()) {
    html = client.DownloadString("http://www.google.com");
}
HtmlDocument doc = new HtmlDocument();        
doc.LoadHtml(html);
foreach(HtmlNode img in doc.DocumentNode.SelectNodes("//img")) {
    Console.WriteLine(img.GetAttributeValue("src", null));
}

Upload and Convert Video to FLV using ASP.NET and Windows Service

Recently I did a project to create an application for a big winter vacation agency. It is photo and video uploading website, where people can upload photos/videos and have their friends vote on them. Photo part is easy, what interesting is the video part. I thought it would be as simple as uploading mp3 files and create flash player to load whatever people have uploded, as my colleague told me, but then I realized that it is not as simple as handling mp3 files because videos have to be converted to FLV in order for flash player to play the video. 
I've done a lot of research but I can't find how to stream WMV, MPG directly from flash, they have to be converted to FLV first. I found a really useful tool that can be used to convert almost any video file to FLV, or to image (JPG, PNG, etc.). It is called ffmpeg, it is an executable file (.EXE). The problem is that it is not a good idea to grant permission for ASP.NET account on the server to be able to run executable file. If people find out about this, then your server is in danger, because people can execute command to format your harddrive, for example. 

The solution was to create a simple windows service program or you can also make desktop application to handle all the video convertion process. The code is shown below:

You probably wonder what flvtool is. We use flvtool to index the FLV file in order to add the correct metadata inside FLV file. 
This is actually a simple form of a youtube-like application. You let people upload videos, convert them to FLV and create thumbnails for the preview. However, this kind of technique doesn't work in a shared hosing environment because you usually can't install any program on the server.

Làm sao để chạy asp.net trên localhost

đây là một câu hỏi mà rất nhiều bạn đã hỏi trung , đây là một vấn đề mà có thể nói là hơi khó hiểu , cài iis asp thường thì chạy rất good còn asp. net thì báo lỗi một cách lạ lùng 



Sao thế nhỉ đây là một lỗi cho chúng ta cài cài VS 2005 hoặc 2003 mà chưa cài IIS Khác...

C# code to publish, delete, retrieve tweets using oauth

The following C#.net class can be used to update statuses, delete, retweet statuses, obtain information regarding a particular status and any body who retweeted a particular status using status id.

This class implements all the methods that are under the “Tweets Resources” section in Twitter API documentation

 

using System;
using System.Text;
using System.Collections.Generic;

namespace TwitterAPI
{
    public class Tweets
    {
        #region Class-Level-Declarations

        private oAuthTwitter OAuth;
        /// <summary>
        /// Create, Update, retrieve, delete tweets(status messages) using this class
        /// </summary>
        /// <param name="_oauth">An authorized and authenticated oAuth token</param>
        public Tweets(oAuthTwitter _oauth)
        {
            this.OAuth = _oauth;
        }
        public enum ResponseFormat { JSON, XML };

        #endregion

        #region Show:ID

        /// <summary>
        /// Returns a single status, specified by the id parameter below. The status's author will be returned inline.
        /// This does not require authentication as long as the status is not protected
        /// This is a rate limited call
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Show_By_ID(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/show/" + statusid + "." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the authenticating user's status. A status update with text identical to the authenticating user's current status will be ignored to prevent duplicates.
        /// Authentication is required and this call is not rate limited
        /// </summary>
        /// <param name="tweet_message">The text of your status update, up to 140 characters.</param>
        /// <param name="reponse_format">The format in which you want twitter to respond</param>
        /// <param name="optionalparameters">Any optional paramters you want to pass</param>
        /// <returns>Response string from twitter in user selected format </returns>
        public string UpdateStatus(ResponseFormat reponse_format, string tweet_message, string optionalparameters)
        {
            if (string.IsNullOrEmpty(tweet_message))
                throw new ArgumentNullException(tweet_message, "The status message cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, "http://api.twitter.com/1/statuses/update." + reponse_format.ToString(), "status=" + tweet_message + optionalparameters);
        }

         #endregion

        #region Destroy:Id

        /// <summary>
        /// Destroys the status specified by the required ID parameter.In other words deletes the specified tweet
        /// Requires authentication, and rate limited is false
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Destroy_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, "http://api.twitter.com/1/statuses/destroy/" + statusid + "." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Retweet:Id

        /// <summary>
        /// Retweets a tweet. Returns the original tweet with retweet details embedded.
        /// Does not require authentication, and rate limited is false
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Retweet_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, "http://api.twitter.com/1/statuses/retweet/" + statusid + "." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Show Retweets:Id

        /// <summary>
        ///Returns up to 100 of the first retweets of a given tweet.
        /// Does not require authentication, and rate limited is false
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Show_Retweets_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/retweets/" + statusid + "." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Show Retweeted By:Id

        /// <summary>
        /// Show user objects of up to 100 members who retweeted the status.
        /// Requires authentication, and rate limited
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Show_Retweetedby_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/" + statusid + "/retweeted_by." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Show Retweeted By:Id

        /// <summary>
        /// Show user ids of up to 100 users who retweeted the status.
        /// Requires authentication, and rate limited
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Show_Retweetedby_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/" + statusid + "/retweeted_by/ids." + response_format.ToString(), optionalparameters);
        }        #endregion
    }
}

 

This class file uses OAuth implementation by shannon whitley (for more information see my previous post Implementing oauth twitter search in C# and JSON).

You can download the complete source code along with this class from https://sites.google.com/site/coderbuddy/downloads/TwitterAPI.zip?attredirects=0&d=1

TwitterAPI.zip (43,25 kb)

How to Post data in C# . NET HttpWebRequest

Cách 1:

public string Post(string url, string data)
{


    string vystup = null;
    try
    {
        //Our postvars
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        //Initialisation, we use localhost, change if appliable
        HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
        //Our method is post, otherwise the buffer (postvars) would be useless
        WebReq.Method = "POST";
        //We use form contentType, for the postvars.
        WebReq.ContentType = "application/x-www-form-urlencoded";
        //The length of the buffer (postvars) is used as contentlength.
        WebReq.ContentLength = buffer.Length;
        //We open a stream for writing the postvars
        Stream PostData = WebReq.GetRequestStream();
        //Now we write, and afterwards, we close. Closing is always important!
        PostData.Write(buffer, 0, buffer.Length);
        PostData.Close();
        //Get the response handle, we have no true response yet!
        HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
        //Let's show some information about the response
        Console.WriteLine(WebResp.StatusCode);
        Console.WriteLine(WebResp.Server);

        //Now, we read the response (the string), and output it.
        Stream Answer = WebResp.GetResponseStream();
        StreamReader _Answer = new StreamReader(Answer);
        vystup = _Answer.ReadToEnd();

        //Congratulations, you just requested your first POST page, you
        //can now start logging into most login forms, with your application
        //Or other examples.
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    return vystup.Trim() + "\n";

}

trong đó data có dạng

string data = "param1=value1&parm2=value2";

Cách 2:

public static string HttpPost(string URI, string Parameters)
{
    // Create a 'HttpWebRequest' object.
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URI);

    CookieContainer cookieJar = new CookieContainer();
    req.CookieContainer = cookieJar;
    req.Referer = "http://captcha.chat.yahoo.com/go/captchat/";
    req.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
    req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6";
    req.KeepAlive = true;
    req.Referer = URI;
    req.ContentType = "application/x-www-form-urlencoded";
    req.Method = "POST";


    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(Parameters);
    req.ContentLength = bytes.Length;

    Stream os = req.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);
    os.Close();

    WebResponse resp = req.GetResponse();
    if (resp == null) return null;

    StreamReader sr = new StreamReader(resp.GetResponseStream());
    return sr.ReadToEnd().Trim();
}

Note: Parameters in my method is the same as

str = "question=" & CaptChaQuestion & "&.intl=us&answer=" & CaptChaAnswer in VB

Cách 3:

using System;
using System.Net;
using System.Web;
using System.Collections;
using System.IO;

namespace WebRequestExample
{

    class WebPostRequest
    {
        WebRequest theRequest;
        HttpWebResponse theResponse;
        ArrayList  theQueryData;

        public WebPostRequest(string url)
        {
            theRequest = WebRequest.Create(url);
            theRequest.Method = "POST";
            theQueryData = new ArrayList();
        }

        public void Add(string key, string value)
        {
            theQueryData.Add(String.Format("{0}={1}",key,HttpUtility.UrlEncode(value)));
        }

        public string GetResponse()
        {
            // Set the encoding type
            theRequest.ContentType="application/x-www-form-urlencoded";

            // Build a string containing all the parameters
            string Parameters = String.Join("&",(String[]) theQueryData.ToArray(typeof(string)));
            theRequest.ContentLength = Parameters.Length;

            // We write the parameters into the request
            StreamWriter sw = new StreamWriter(theRequest.GetRequestStream());
            sw.Write(Parameters);
            sw.Close();

            // Execute the query
            theResponse =  (HttpWebResponse)theRequest.GetResponse();
            StreamReader sr = new StreamReader(theResponse.GetResponseStream());
            return sr.ReadToEnd();
        }

    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            WebPostRequest myPost = new WebPostRequest("http://www.dijksterhuis.org/test/post.php");
            myPost.Add("keyword","void");
            myPost.Add("data","hello&+-[]");
            Console.WriteLine(myPost.GetResponse());
        }
    }
}

Cách 4:

public class RemotePost
{
    private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();
    private string Url = string.Empty;

    /// <summary>
    /// number of seconds for timeout
    /// </summary>
    public int Timeout = 0;

    /// <summary>
    /// Url to post to
    /// </summary>
    public RemotePost(string url)
    {
        Url = url;
    }

    /// <summary>
    /// Parameters to add to the post
    /// </summary>
    /// <param name="name">parameter name</param>
    /// <param name="value">parameter value</param>
    public void Add(string name, string value)
    {
        Inputs.Add(name, value);
    }

    /// <summary>
    /// Posts data to server using POST method
    /// </summary>
    /// <returns></returns>
    public string Post()
    {
        string postData = String.Empty;

        int keyscount = Inputs.Keys.Count;

        for (int i = 0; i < keyscount; i++)
            postData += "&" + Inputs.Keys[i] + "=" + HttpUtility.UrlEncode(Inputs[Inputs.Keys[i]]);

        if (postData.Length > 0)
            postData = postData.Substring(1);

        HttpWebRequest wr = WebRequest.Create(Url) as HttpWebRequest;
        wr.Method = "POST";
        wr.ContentType = "application/x-www-form-urlencoded";

        using (StreamWriter requestWriter = new StreamWriter(wr.GetRequestStream()))
        {
            requestWriter.Write(postData);
        }

        return GetResponse(wr);
    }

    /// <summary>
    /// Posts data to server using GET method
    /// </summary>
    /// <returns></returns>
    public string Get()
    {
        string postData = String.Empty;

        int keyscount = Inputs.Keys.Count;

        for (int i = 0; i < keyscount; i++)
            postData += "&" + Inputs.Keys[i] + "=" + HttpUtility.UrlEncode(Inputs[Inputs.Keys[i]]);

        if (postData.Length > 0)
            postData = postData.Substring(1);

        string postUrl = Url.Contains("?") ? (Url + "&" + postData) : (Url + "?" + postData);

        HttpWebRequest wr = WebRequest.Create(postUrl) as HttpWebRequest;
        wr.Method = "GET";

        return GetResponse(wr);
    }

    private string GetResponse(HttpWebRequest wr)
    {
        wr.Timeout = Timeout * 1000; //millisecond timeout

        HttpWebResponse response = (HttpWebResponse)wr.GetResponse();

        if (response.StatusCode != HttpStatusCode.OK)
            return String.Empty;

        using (Stream responseStream = response.GetResponseStream())
        {
            using (StreamReader readerStream = new StreamReader(responseStream, System.Text.Encoding.UTF8))
            {
                return readerStream.ReadToEnd();
            }
        }
    }
}
Cách sử dụng:
RemotePost req = new RemotePost(postUrl);
req.Timeout = 3;

req.Add("FirstName", "First");
req.Add("LastName", "Last");

string response = req.Post();
string response = req.Get();

Chúc vui