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));
}

Sử dụng Transaction trong SQL Server

Có 2 cách để kiểm soát Transaction trong SQL Server
Cách 1: bằng cách kiểm tra biến toàn cục @@ERROR để xác định nếu có lỗi xảy ra thì thực hiện rollback. Đây là cách cổ điển của SQL Server 2000. Điểm bất tiện của nó là sau mỗi câu lệnh SQL, ta phải thực hiện việc kiểm tra giá trị của biến này, để kịp thời rollback.

CREATE PROC For_TransTest
AS
BEGIN
    BEGIN TRANSACTION updatestaff;

    UPDATE aspnet.staff SET fk_department = 30
    WHERE pk_staff = 971;

    IF @@ERROR != 0  -- neu co loi xay ra, rollback 
    BEGIN
        PRINT 'rollback ne';
        ROLLBACK TRAN updatestaff;
    END

    UPDATE aspnet.staff SET fk_department = null
    WHERE pk_staff = 971;

    IF @@ERROR != 0  -- neu co loi xay ra, rollback 
    BEGIN
        PRINT 'rollback ne';
        ROLLBACK TRAN updatestaff;
    END
    ELSE
        COMMIT TRANSACTION updatestaff;

END
Cách 2: Sử dụng lệnh TRY...CATCH, hỗ trợ trên SQL Sever 2005, rất đơn giản và dễ dùng
CREATE PROC For_TransTest
AS
BEGIN
    BEGIN TRY

        BEGIN TRANSACTION updatestaff;

        UPDATE aspnet.staff SET fk_department = 30
        WHERE pk_staff = 971;

        UPDATE aspnet.staff SET fk_department = null
        WHERE pk_staff = 971;


        COMMIT TRANSACTION updatestaff;
        PRINT 'commited';
    END TRY
    BEGIN CATCH
        PRINT 'rollback ne';
        ROLLBACK TRAN updatestaff;  
    END CATCH
END

Extract query string from an url (Csharp)

Nếu có một lúc nào đó cần lấy paramater (query string) trong chuỗi URL, hãy nhớ tới bài viết này. He he

C# đã cung cấp một hàm để phân tích các paramater trong URL thành một mảng [name, value].

HttpUtility.ParseQueryString(string query)

Chẳng hạn, ta có URL như sau: http://test.abc?p1=1&p2=2

Từ đây, chúng ta cần lấy phần query phía sau dấu chấm hỏi:

string url = "http://test.abc?p1=1&p2=2";
string query = url.Split('?')[1];
/*--> query = p1=1&p2=2 */

Giờ chỉ việc gọi hàm và lấy giá trị thôi.

NameValueCollection array = HttpUtility.ParseQueryString(query);

string p1 = array.Get("p1");
string p2 = array.Get("p2");
Tóm gọn lại:
public NameValueCollection ExtractParamUrl(string url)
{
    if (string.IsNullOrEmpty(url) || url.IndexOf('?') < 0)
        return null;

    string query = url.Split('?')[1];

    return HttpUtility.ParseQueryString(query);
}

 

Convert Audio, Video to Any Format using C#

Have you ever wondered how VLC is able to play almost any kind of video or audio format, yet many others cannot? The secret behind VLC is ffplay, an amazing open source project that combines hundreds of codecs into one small library. The people that made ffplay also made ffmpeg, which, among many other things, can convert any video or audio file to almost any kind of format. 

Project link: http://ffmpeg.org/

Note: You’ll need to either download and build the executable from the source code, or much easier, you can download a Win32 or Win64 build from an ffmpeg unofficial build provider:

Download link: http://ffmpeg.arrozcru.org/builds/

The library supports tens of codecs, many that are obsolete or that no one has heard of. The library is very configurable but also very smart, guessing most of the media’s parameters (resolution, bit rate, etc.) without you having to input it. Just give this library a source file and a destination file and format, and it will do the rest. 

In this article, I’ll briefly describe an attached ffmpeg C# wrapper I wrote so that you can bring this enormously useful tool to your applications. I abstracted the actual conversion logic, so that you can plug in your converter into my shell using the following interface:

public interface IConverter
{
       Process StartConversion(Conversion conversion);
}
The StartConversion method takes a Conversion object, which holds the input, output destinations, the final format, and some other properties. It returns a System.Diagnostics.Process object which is the .NET representation of a Windows process. 

If you want to plug in your own IConverter, you can extend my class ConversionManager and override the method:

protected override IConverter CreateConverter(string converterPath)
{
       return new FFMpegWrapper(converterPath);
}
where FFMpegWrapper is your IConverter.

You can use my FFMpegWrapper directly too without using the ConversionManager, but both need to be initialized with the path to the ffmpeg.exe  executable on your machine. 

The ConversionManager method supports synchronous and asynchronous conversion. It will also manage one or more async conversions for you, and exposes events for when the conversion starts, progresses, and finishes. 

Here is a basic overview of the public methods provided:

public void Convert(string source, string destination)

public void Convert(string source, string destination, string optionalArguments)

public Conversion ConvertAsync(string source, string destination)

public Conversion ConvertAsync(string source, string destination, string optionalArguments)
However, since I am just started a separate process and channeling the output through the event, the my wrapper won’t actually know how much of the conversion is left, or whether it finished successfully. It will just know when it finished. 

If you are interested, take a look at the provided project to see how I wrap the ffmpeg executable using System.Diagnostics.ProcessStartInfo. 

Enjoy your converted media!

Ivolo.Tools.Conversion Source.zip (4,33 kb)

Ivolo.Tools.Conversion_win32.dll (9,50 kb)

YouTubery: A Tool to Automatically Download and Convert YouTube Videos to Avi, Mpeg, Mp3, or Burn Them to DVDs

As far as I know, YouTube has blocked the get_video web service. If they release another public web service to download flv's, I or anyone else can extend the library described here by adding an IResolver provider. But for now, it seems this library will not work for downloading YouTube videos. Apologies.

 In my recent two posts, I talked about downloading YouTube videos using C#, and converting audio, video to any imaginable format using FFMpeg. Hopefully not surprising is the fact that these two tutorials can be combined to form a fairly useful tool.

I know I often wished that I could download YouTube videos so that I could watch them offline or listen to them in mp3 form. The application attached at the bottom of this article lets you do just that. You can input a list of YouTube urls and the app will download them, and convert them to any format you specify including avi, mpeg, mp3, wave, etc. After you are done downloading, you can click Burn DVD and the program will automatically import all the downloaded content into Windows DVD Maker for burning.

The app uses WPF for a simple UI, and DownloadManager and ConversionManager libraries (from my previous two articles) for the downloading and converting respectively. It allows for any number of concurrent downloads and conversions to happen.

Using these two libraries to create this app couldn’t be simpler. It’s as simple as creating these two managers and subscribing to started, progressed, finished events. The main window just features a table of “download row” controls, a browse control for the output path, and a textbox for the output format.

I am attaching the source code as well so anyone interested can see an easy example of using my download, converting libraries. I hope you find use in the app, and as always, report any problems to me below. Thanks!

Youtubery.zip (3,50 mb)

YouTubery source code.zip (188,25 kb)