5/22/2012

Tips writing jQuery function for beginner

Wirting jQuery

   1:  //----------------------------------------------
   2:  //a shortcut code noConflict 
   3:  (function($) {
   4:      // do something on document ready
   5:  })(jQuery);
      
   7:  //a long code
   8:  $(document).ready(function() {
   9:      // put all your jQuery goodness in here.
  10:  });
     
  12:  //a shortcut code
  13:  $(function() {
  14:      // do something on document ready
  15:  });

Fix error Conflict between many javascript library

//----------------------------------------------
//(noConflict) see reference site: http://api.jquery.com/jQuery.noConflict/
//Many JavaScript libraries use $ as a function or variable name,
//just as jQuery does. In jQuery's case, $ is just an alias for jQuery,
//so all functionality is available without using $.
//If we need to use another JavaScript library alongside jQuery,
// we can return control of $ back to the other library with a call to $.noConflict():
$.noConflict();
//or
jQuery.noConflict();
// Code that uses other library's $ can follow here.

Multiple $(document).ready() in one javascript file

$(document).ready(function() {
    // some code here
});
$(document).ready(function() {
    // other code here
});

Function define in one $(document).ready block and call outside another $(document).ready block

var demoFunction;
$(document).ready(function() {
    // some code here
    demoFunction = function() {
        // some function that does stuff
    };
});

$(document).ready(function() {
    demoFunction();
});

continuous….

Save And Share :

5/19/2012

Get URL after Rewrite in C#

When you use the URL rewrite module in C# with mod_rewrite rules like  www.domain.com/products/clothes

you can easy to get anything after www.domain.com by use below code

HttpContext context = HttpContext.Current; string value = context.Request.RawUrl;

and you can get it /products/clothes  .Using function Regex to Split that string

string[] url = Regex.Split(value, Regex.Escape("/"));

Save And Share :

5/18/2012

Sys.WebForms.PageRequestManagerParserErrorException

When I try use Ajax ScriptManager to update panel, I have a trouble with an error :

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.

After just I Rebuild all project and no see last error but found another error:

Uncaught Sys.ParameterCountException: Sys.ParameterCountException: Parameter count mismatch.

now i don’t know how to fix it

Save And Share :

5/15/2012

Paging in SQL Server 2005 (ROW_NUMBER() - Select dữ liệu trả về trong 1 khoảng)

Introduction

Developers and database administrators have long debated methods for paging recordset results from Microsoft SQL Server, trying to balance ease of use with performance. The simplest methods were less efficient because they retrieved entire datasets from SQL Server before eliminating records which were not to be included, while the best-performing methods handled all paging on the server with more complex scripting. The ROW_NUMBER() function introduced in SQL Server 2005 provides an efficient way to limit results relatively easily.

Paging Efficiency

In order to scale well, most applications only work with a portion of the available data at a given time. Web-based data maintenance applications are the most common example of this, and several data-bindable ASP.NET classes (such as GridView and Datagrid) have built-in support for paging results. While it is possible to handle paging within the web page code, this may require transferring all of the data from the database server to the web server every time the control is updated. To improve performance and efficiency, data which will not be used should be eliminated from processing as early as possible.

Paging Methods

Many popular databases offer functions allowing you to limit which rows are returned for a given query based upon their position within the record set. For example, MySQL provides the LIMIT qualifier, which takes two parameters. The first LIMIT parameter specifies which (zero-based) row number will be the first record returned, and the second parameter specifies the maximum number of records returned. The query:

SELECT * FROM table LIMIT 20,13

...will return the 20th through the 32nd records -- assuming at least 33 records are available to return. If fewer than 33 records are available, the query will return all records from record 20 on. If fewer than 20 records are available, none will be returned.

SQL Server does not have this functionality, however the 2005 release does have a number of other new tricks. For instance, support for CLR procedures means it is possible to use existing paging methods to write VB.NET or C# code that would execute within the SQL Server environment. Unfortunately, CLR procedures are not as efficient as native Transact SQL. To ensure best performance, queries should still be written in TSQL whenever practical.

Using ROW_NUMBER()

TSQL in the 2005 release includes the ROW_NUMBER() function, which adds an integer field to each record with the record's ordinal result set number. Stated more simply, it adds the record's position within the result set as an additional field so that the first record has a 1, the second a 2, etc. This may appear to be of little value, however by using nested queries we can use this to our advantage.

To demonstrate ROW_NUMBER() and to explore how the paging solution works, create a simple salary table and populate it with random data using the following commands:

CREATE TABLE [dbo].[Salaries](
    [person] [nvarchar](50) NOT NULL,
    [income] [money] NOT NULL,
 CONSTRAINT [PK_salaries] PRIMARY KEY CLUSTERED(
    [person] ASC
)) ON [PRIMARY]
GO

INSERT INTO Salaries VALUES ('Joe', '28000')
INSERT INTO Salaries VALUES ('Sue', '96000')
INSERT INTO Salaries VALUES ('Michael', '45000')
INSERT INTO Salaries VALUES ('John', '67000')
INSERT INTO Salaries VALUES ('Ralph', '18000')
INSERT INTO Salaries VALUES ('Karen', '73000')
INSERT INTO Salaries VALUES ('Waldo', '47000')
INSERT INTO Salaries VALUES ('Eva', '51000')
INSERT INTO Salaries VALUES ('Emerson', '84000')
INSERT INTO Salaries VALUES ('Stanley', '59000')
INSERT INTO Salaries VALUES ('Jorge', '48000')
INSERT INTO Salaries VALUES ('Constance', '51000')
INSERT INTO Salaries VALUES ('Amelia', '36000')
INSERT INTO Salaries VALUES ('Anna', '49000')
INSERT INTO Salaries VALUES ('Danielle', '68000')
INSERT INTO Salaries VALUES ('Stephanie', '47000')
INSERT INTO Salaries VALUES ('Elizabeth', '23000')

The ROW_NUMBER() function has no parameters - it simply adds the row number to each record in the result set. To ensure the numbering is consistent, however, SQL Server needs to know how to sort the data. Because of this, ROW_NUMBER() must immediately be followed by the OVER() function. OVER() has one required parameter, which is an ORDER BY clause. The basic syntax for querying the Salaries table is:

SELECT ROW_NUMBER() OVER(ORDER BY person), person, income
FROM Salaries

 

This returns the following result:
 
(No column name)    person    income
1    Amelia    36000.00
2    Anna    49000.00
3    Constance    51000.00
4    Danielle    68000.00
5    Elizabeth    23000.00
6    Emerson    84000.00
7    Eva    51000.00
8    Joe    28000.00
9    John    67000.00
10    Jorge    48000.00
11    Karen    73000.00
12    Michael    45000.00
13    Ralph    18000.00
14    Stanley    59000.00
15    Stephanie    47000.00
16    Sue    96000.00
17    Waldo    47000.00
The Salaries data now appears sorted by person, and it has an extra column indicating each record's position within the results.
 
If for any reason you wanted the results to display in a different order than they were numbered in, you can include a different ORDER BY clause as part of the normal SELECT syntax:

 

SELECT ROW_NUMBER() OVER(ORDER BY person), person, income 
FROM Salaries 
ORDER BY income

This returns the following result:
 
(No column name)    person    income
13    Ralph    18000.00
5    Elizabeth    23000.00
8    Joe    28000.00
1    Amelia    36000.00
12    Michael    45000.00
15    Stephanie    47000.00
17    Waldo    47000.00
10    Jorge    48000.00
2    Anna    49000.00
3    Constance    51000.00
7    Eva    51000.00
14    Stanley    59000.00
9    John    67000.00
4    Danielle    68000.00
11    Karen    73000.00
6    Emerson    84000.00
16    Sue    96000.00
If we want to limit the results displayed to a certain range, we need to nest this SELECT inside another one and provide a name for the ROW_NUMBER() column. To limit our results to records 5 through 9, we can use the following query:

 

SELECT *
FROM   (SELECT ROW_NUMBER() OVER(ORDER BY person) AS 
       rownum, person, income FROM Salaries) AS Salaries1
WHERE  rownum >= 5 AND rownum <= 9

This returns the following result:

rownum    person    income
5    Elizabeth    23000.00
6    Emerson    84000.00
7    Eva    51000.00
8    Joe    28000.00
9    John    67000.00
Again, we can change the sort order by adding an ORDER BY clause. This is most easily accomplished by using the outer SELECT statement:

SELECT *
FROM   (SELECT ROW_NUMBER() OVER(ORDER BY person) AS
       rownum, person, income FROM Salaries) AS Salaries1
WHERE  rownum >= 5 AND rownum <= 9
ORDER BY income

This returns the following result:

rownum    person    income
5    Elizabeth    23000.00
8    Joe    28000.00
7    Eva    51000.00
9    John    67000.00
6    Emerson    84000.00
If we want to support the same type of arguments that MySQL's LIMIT() supports, we can create a stored procedure that accepts a beginning point and a maximum number of records to return. ROW_NUMBER requires that the data be sorted, so we will also have a required parameter for the ORDER BY clause. Execute the following statement to create a new stored procedure:

CREATE PROCEDURE [dbo].[pageSalaries]
  @start  int = 1
 ,@maxct  int = 5
 ,@sort   nvarchar(200)
AS
  SET NOCOUNT ON
  DECLARE
    @STMT nvarchar(max),    -- SQL statement to execute
    @ubound int

  IF @start < 1 SET @start = 1
  IF @maxct < 1 SET @maxct = 1
  SET @ubound = @start + @maxct
  SET @STMT = ' SELECT person, income
                FROM (
                      SELECT  ROW_NUMBER() OVER(ORDER BY ' + @sort + ') AS row, *
                      FROM    Salaries
                     ) AS tbl
                WHERE  row >= ' + CONVERT(varchar(9), @start) + ' AND
                       row <  ' + CONVERT(varchar(9), @ubound)
  EXEC (@STMT)              -- return requested records 

The pageSalaries procedure begins with SET NOCOUNT ON to disable the record count message (a common step for optimizing query performance). We then declare two necessary variables, @STMT and @ubound. Because we want to be able to change what ORDER BY argument is used, we need to dynamically generate our query statement by storing it in @STMT. The next lines ensure that only positive numbers are used for the starting position and maximum size, then calculate the range of ROW_NUMBER() values being requested. (If we wanted to be zero-based like MySQL's LIMIT, we could do so with a few minor tweaks.) Once the dynamic SQL command has been strung together, it is executed so that the results are returned.

Execute the following statement to test the stored procedure:

pageSalaries 4, 7, 'income'

This returns the following result:

person    income
Amelia    36000.00
Michael    45000.00
Stephanie    47000.00
Waldo    47000.00
Jorge    48000.00
Anna    49000.00
Constance    51000.00
If we execute:

pageSalaries 13, 7, 'income'

we receive back:

person    income
John    67000.00
Danielle    68000.00
Karen    73000.00
Emerson    84000.00
Sue    96000.00
... because the query goes beyond the number of records available.

Taking this one step further, we can make a stored procedure that does a more general form of paging. In fact, it can be generalized to the point that it can be used to return any collection of fields, in any order, with any filtering clause. To create this wunderkind marvel, execute the following command:

CREATE PROCEDURE [dbo].[utilPAGE]
  @datasrc nvarchar(200)
 ,@orderBy nvarchar(200)
 ,@fieldlist nvarchar(200) = '*'
 ,@filter nvarchar(200) = ''
 ,@pageNum int = 1
 ,@pageSize int = NULL
AS
  SET NOCOUNT ON
  DECLARE
     @STMT nvarchar(max)         -- SQL to execute
    ,@recct int                  -- total # of records (for GridView paging interface)

  IF LTRIM(RTRIM(@filter)) = '' SET @filter = '1 = 1'
  IF @pageSize IS NULL BEGIN
    SET @STMT =  'SELECT   ' + @fieldlist + 
                 'FROM     ' + @datasrc +
                 'WHERE    ' + @filter + 
                 'ORDER BY ' + @orderBy
    EXEC (@STMT)                 -- return requested records 
  END ELSE BEGIN
    SET @STMT =  'SELECT   @recct = COUNT(*)
                  FROM     ' + @datasrc + '
                  WHERE    ' + @filter
    EXEC sp_executeSQL @STMT, @params = N'@recct INT OUTPUT', @recct = @recct OUTPUT
    SELECT @recct AS recct       -- return the total # of records

    DECLARE
      @lbound int,
      @ubound int

    SET @pageNum = ABS(@pageNum)
    SET @pageSize = ABS(@pageSize)
    IF @pageNum < 1 SET @pageNum = 1
    IF @pageSize < 1 SET @pageSize = 1
    SET @lbound = ((@pageNum - 1) * @pageSize)
    SET @ubound = @lbound + @pageSize + 1
    IF @lbound >= @recct BEGIN
      SET @ubound = @recct + 1
      SET @lbound = @ubound - (@pageSize + 1) -- return the last page of records if                                               -- no records would be on the
                                              -- specified page
    END
    SET @STMT =  'SELECT  ' + @fieldlist + '
                  FROM    (
                            SELECT  ROW_NUMBER() OVER(ORDER BY ' + @orderBy + ') AS row, *
                            FROM    ' + @datasrc + '
                            WHERE   ' + @filter + '
                          ) AS tbl
                  WHERE
                          row > ' + CONVERT(varchar(9), @lbound) + ' AND
                          row < ' + CONVERT(varchar(9), @ubound)
    EXEC (@STMT)                 -- return requested records 
  END

You may receive the following error message from SQL Server, which you can confidently ignore:

Cannot add rows to sys.sql_dependencies for the stored procedure because it depends on the missing table 'sp_executeSQL'. The stored procedure will still be created; however, it cannot be successfully executed until the table exists.
The utilPage procedure accepts 6 parameters:

@datasrc            - the table (or stored procedure, etc.) name
@orderBy    - the ORDER BY clause
@fieldlis    - the fields to return (including calculated expressions)
@filter    - the WHERE clause
@pageNum    - the page to return (must be greater than or equal to one)
@pageSize    - the number of records per page
The stored procedure needs the name of a data source to query against (such as a table) and one or more fields to sort by (since OVER() requires an ORDER BY clause). If @filter is blank (the default), it will be set to "1 = 1" as a simple way to select all records. If @pageSize is not supplied, the query will run without paging and will not return a record count.

If, however, @pageSize is supplied, a version of the query is executed to get the total number of records. In order to have this record count available within the procedure and as a returned value, we use sp_executeSQL to support executing the statement while returning an output parameter. The record count is used to prevent returning empty results when possible, and to support paging interfaces that calculate the number of pages available (such as GridView). If we were calling this stored procedure to populate a GridView, we would return @recct as a ReturnValue parameter instead of using a result set, but we will use a result set for demonstration purposes.

The procedure calculates what the actual record positions will be for the requested page. Rather than allow the query to fail, there are safety checks ensuring that @pageSize and @pageNum are greater than zero, and that the result set will not be empty. If the specified page is out of range, this procedure will return the last possible page of records. This is helpful if a user changes more than one setting before refreshing their data, or if a significant amount of data is deleted between requests.

The remainder of the procedure is virtually identical to the pageSalaries procedure. To test the utilPAGE stored procedure, execute the following statement:

utilPAGE 'Salaries', 'person', '*', 'income > 1000', 2, 4

This returns the following two result sets:

recct
17

row    person    income
5    Elizabeth    23000
6    Emerson    84000
7    Eva    51000
8    Joe    28000
If we execute:

utilPAGE 'Salaries', 'person', 'person, income', '', 13, 3

...we receive back:

recct
17

person    income
Stephanie    47000
Sue    96000
Waldo    47000
Even though the request should be for records 36 through 38 - far outside of what is available - the procedure returns the last available page of records. In contrast, requesting the third page with seven records per page using:

utilPAGE 'Salaries', 'person', 'person, income', '', 3, 7

...returns the last three records, as the page is not completely out of bounds:

person    income
Stephanie    47000
Sue    96000
Waldo    47000
All of these examples are based on simple single-table queries, which may not reflect what you need in the real world. While the utilPAGE procedure does not support ad-hoc JOINs, it does work with SQL Views. If you want paging support for multi-table queries, you should create a View (with all of the necessary JOINs) to use as the data source. Using a View follows good design practices as it ensures that your Joins are performed consistently, allows easier ad-hoc querying from the command line, and is much easier to troubleshoot than a stored procedure's dynamic SELECT statement logic.

Conclusion


While SQL Server does not have as simple a method for paging results as some other databases, features introduced in the 2005 release have made it possible to page results efficiently more easily than ever before. In the next article in this series, we will go a step further and integrate this paging logic with a GridView through a Data Access Layer. 

------------------------------------------------------------

Demo:

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

go

 

 

-- =============================================       

-- Author:  TaiTD     

-- Create date: 02/02/2010

-- Description: Export to XML file       

-- =============================================       

ALTER proc [dbo].[GetDELETEDJobPostingsBy_JobTypeID]       

(

      @JobTypeID int

)

As       

Begin     

 

      SELECT *

      FROM   (SELECT ROW_NUMBER() OVER(ORDER BY del.JobPostingID) AS

               rownum, del.JobPostingID, del.Title, del.Description, del.IsSearchable, JT.JobTypeID, JST.JobSubTypeID,

                  JT.JobTypeKey, JST.JobSubtypeKey, com.CompanyName, com.CompanyProfile

                  FROM DELETED_JobPostings as del

                  INNER JOIN Web_Companies as com ON del.CompanyID = com.CompanyID

                  JOIN DELETED_JobPostings_Types as delJPT ON delJPT.JobPostingID = del.JobPostingID

                  JOIN Web_JobSubtypes as JST ON JST.JobSubtypeID = delJPT.JobSubtypeID

                  JOIN Web_JobTypes as JT ON JT.JobTypeID = JST.JobTypeID ) AS OOOOO

      WHERE IsSearchable=1 and LEN(Description)>100 and rownum >= 1 AND rownum <= 170000 and JobTypeID=@JobTypeID

           

End

 

--------------

--          SELECT top 9000 del.JobPostingID, del.Title, del.Description, del.IsSearchable, JT.JobTypeID, JST.JobSubTypeID,

--          JT.JobType, JST.JobSubType, com.CompanyName, com.CompanyProfile

--          FROM DELETED_JobPostings as del

--          INNER JOIN Web_Companies as com ON del.CompanyID = com.CompanyID

--          JOIN DELETED_JobPostings_Types as delJPT ON delJPT.JobPostingID = del.JobPostingID

--          JOIN Web_JobSubtypes as JST ON JST.JobSubtypeID = delJPT.JobSubtypeID

--          JOIN Web_JobTypes as JT ON JT.JobTypeID = JST.JobTypeID

--          WHERE del.IsSearchable=1 and LEN(del.Description)>100 and JT.JobTypeID=@JobTypeID

----------------

--SELECT *

--FROM   (SELECT ROW_NUMBER() OVER(ORDER BY JobPostingID) AS

--       rownum, JobPostingID, Title FROM DELETED_JobPostings) AS del

--WHERE  rownum >= 5 AND rownum <= 9

----------------

--

--SELECT *

--FROM   (SELECT ROW_NUMBER() OVER(ORDER BY del.JobPostingID) AS

--       rownum, del.JobPostingID, del.Title, del.Description, del.IsSearchable, JT.JobTypeID, JST.JobSubTypeID,

--          JT.JobType, JST.JobSubType, com.CompanyName, com.CompanyProfile

--          FROM DELETED_JobPostings as del

--          INNER JOIN Web_Companies as com ON del.CompanyID = com.CompanyID

--          JOIN DELETED_JobPostings_Types as delJPT ON delJPT.JobPostingID = del.JobPostingID

--          JOIN Web_JobSubtypes as JST ON JST.JobSubtypeID = delJPT.JobSubtypeID

--          JOIN Web_JobTypes as JT ON JT.JobTypeID = JST.JobTypeID ) AS OOOOO

--WHERE IsSearchable=1 and LEN(Description)>100 and JobTypeID=@JobTypeID and rownum >= 5 AND rownum <= 9

------------------

Save And Share :

5/14/2012

Add Social Sharing Button to Blogger

Messenger
   1:  <span class='post-share'> <p>
   2:   
   3:  Save And Share : 
   4:   
   5:  <a expr:href='&quot;http://twitter.com/intent/tweet?text=&quot; + data:post.title + &quot;&amp;url=&quot; + data:post.url' target='_blank' title='Tweet This !'><img alt='Tweet This !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCcBZqLbjK3fBwQnjANcDxKkSeNtPQ5aNpDrUn4X3PiiCQy4p_fE_wXPVexWGioTTipnNb60XXCZUoXLPFfdIqpR9j-TG8J-bsejM8nu_ImMnuRsI0xRweVbHnfsgbdAiFTaiiQ7wCsuY/' style='height:16px; width:16px; padding:0; border:0; vertical-align:middle;'/></a> 
   6:   
   7:  <a expr:href='&quot;http://www.facebook.com/sharer.php?u=&quot; + data:post.url + &quot;&amp;t=&quot; + data:post.title' target='_blank' title='Share On Facebook !'><img alt='Share On Facebook !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjURNYcuObzGHoRjtwTqr2znKyzLZz0xvccAA-48DsZn9WCjqBKx3Oc-765djMXMdss1y9Xc-pTWfGE5N71mqCiAbLiVDXc4eThdjhUlp8Fx7ogCMU7pc6J8GowxwCeWq0dxMubZu0VMO0/' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
   8:   
   9:  <a expr:href='&quot;https://plusone.google.com/_/+1/confirm?hl=&quot; + &quot;en&amp;url=&quot; + data:post.url' target='_blank' title='Share On Google Plus !'><img alt='Share On Google Plus !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjaV54Zgh8PheChwosthA_pTnHIRoPZz3NqcYVXUSYrFqvxE2oa0v4wiiKTY7QB6CcBYBZPpAM2lyrMlViHOXBY02gFgk_fhh2hehnBm73wyWaygdrpXDmWeMoJEin4muOAmgXS_XI12uY/s16/icon-google-plus.gif' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  10:   
  11:  <a expr:href='&quot;http://del.icio.us/post?url=&quot; + data:post.url + &quot;&amp;title=&quot; + data:post.title' target='_blank' title='Add To Del.icio.us !'><img alt='Add To Del.icio.us !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiBPkbvMGGEkwDN62YuoF4ep8V1s8EFz-zmZiQDiPVR4v0kRlxkGGorNp40vCV5K5vt_RFCWgzefsQCMtNgV-b4xWWLenHO2OZyY3xQRaiHSvGEBhyphenhyphenAeBV38GQebH42XIh8dEkGbZXaec/' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  12:   
  13:  <a expr:href='&quot;http://www.stumbleupon.com/submit?url=&quot; + data:post.url + &quot;&amp;title=&quot; + data:post.title' target='_blank' title='Share On StumbleUpon !'><img alt='Share On StumbleUpon !' src='https://lh3.googleusercontent.com/-uXMuiLzxoFM/T25RKdHPgoI/AAAAAAAAARg/iU-TbKOb174/s16/stumble-new.gif' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  14:   
  15:  <a expr:href='&quot;http://digg.com/submit?phase=&quot; + &quot;2&amp;url=&quot; + data:post.url + &quot;&amp;title=&quot; + data:post.title' target='_blank' title='Share On Digg !'><img alt='Share On Digg !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjsHf71cFfhaR41ZqVFrpfchm1ZEva5lcG5feIaq7vNdLImBdcnzax6_3vZI0fFQ5KdCeSSj05k15ihbekdeOJ0u6CORqS0LqmlkFenr9iPpf1zlZwSGaj_LtK_74iisTXiMqm7oBpQKcM/' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  16:   
  17:  <a expr:href='&quot;http://pinterest.com/pin/create/button/?url=&quot; + data:post.url + &quot;&amp;title=&quot; + data:post.title + &quot;&amp;is_video=&quot;' target='_blank' title='Pin It !'><img alt='Pin It !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtTalRNJBvJvILFUXp3tzrduELUyN9mcVvugtCKM96Y4XwsADcAW6-RqLR9lcLYRhta4fgk9uPmvqQnZ3U1-w2w-iVOiNK7UurZcwTfVBm3ioRVYQJSQiW2asro_J8KiiUq3Uxt2mbGMc/s16/pinterest-button.gif' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  18:   
  19:  <a expr:href='&quot;http://reddit.com/submit?url=&quot; + data:post.url + &quot;&amp;title=&quot; + data:post.title' target='_blank' title='Share On Reddit !'><img alt='Share On Reddit !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj3LUJKCEpvwgJf_yv2pLK4aBusD_TJgXaFsJKPjXar2HwbKSfHPuJxJeAg1W0Nx85J3NL5CYikYQyfEWa5e7W1vYif2qktzDHd9yIyjby-eN5BmHHTzQjSpLXfl0l4HB8Pw2aV5hl-38U/' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  20:   
  21:  <a expr:href='&quot;http://www.linkedin.com/shareArticle?mini=&quot; + &quot;true&amp;url=&quot; + data:post.url + &quot;&amp;title=&quot; + data:post.title' target='_blank' title='Share On LinkedIn !'><img alt='Share On LinkedIn !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh5kgu05yH5Hvol5imREiYO_mh3nkB8rK2IAm0gk9Alol80d0_wxh0CTdop_CNsVnJjlDGqFDakKEGZzZ7T13Sl-BJihWvJXECS24bxNqq8YfdQDyeym6xAidT9XGIJkLx4w6hkQ1yPCBI/' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  22:   
  23:  <a expr:href='&quot;http://www.blogger.com/blog_this.pyra?t&quot; + &quot;&amp;u=&quot; + data:post.url + &quot;&amp;n=&quot; + data:post.title + &quot;&amp;pli=&quot; + 1' target='_blank' title='Post To Blogger !'><img alt='Post To Blogger !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiMAtYCJnak2wbWGkCFecaKE-s1QbiniMzY0qgXCZbVxWyn2RBpPs3HbZk6kHUt0f2bPkxvljKtTu7SxcGXq1L0OyPVxw6n0VHhSpO421L-aWQiZhAHW4-5Pu_18JCYIVnDrKvlpleAk18/' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  24:   
  25:  <a expr:href='&quot;http://www.friendfeed.com/share?link=&quot; + data:post.url + &quot;&amp;title=&quot; + data:post.title' target='_blank' title='Share On Friend Feed !'><img alt='Share On Friend Feed !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-IF_VAEiyeJKl7BxcB0boFcuASdNELRSNeyzfhhoybm1k3ZRCVFHzgsZS5AuDVqrHMZ5KZ8OyQRTwzX_W4B6j4FGTD3xpHNMLat35FAOV5BKWyJoYMDfUkWcD4KTV6Hv-BuT5Ns2P6z0/' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  26:   
  27:  <a expr:href='&quot;http://www.myspace.com/Modules/PostTo/Pages/?u=&quot; + data:post.url + &quot;&amp;t=&quot; + data:post.title' target='_blank' title='Share On MySpace !'><img alt='Share On MySpace !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj3vfyoYKFRk7olcZ0cQnjB_SQfYa-TDbUygd_hKK0PIbhBCLvjHutJWAsgz_PxSxroFu7e9h4JhtcD9-JYG7dHRtfuw_75_JSK6xc_UTXXYo596N0bGFLk9PRk5P7GZxOxkpkk8uCdWC4/' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  28:   
  29:  <a expr:href='&quot;http://buzz.yahoo.com/buzz?targetUrl=&quot; + data:post.url + &quot;&amp;headline=&quot; + data:post.title' target='_blank' title='Share On Yahoo Buzz !'><img alt='Share On Yahoo Buzz !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpXBRsn2aUEIdVbVui3fHoOYavx0Vzv3mxOTVFErJxge-ccYULV40ar4PT6Mi3Cr0lexUQsgZA1-dk5NqT09p9BK_iPfJPZlxdOUMXU82cCtgFtzXyIxMJKu8cWMp3qnh2NekZ5f-VNkc/' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  30:   
  31:  <a href='http://love4all1080.blogspot.com/2010/01/simple-share-buttons-for-blogger.html' target='_blank' title='Get These Share Buttons !'><img alt='Get These Share Buttons !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPfEK2VNAbQPk5xums_gSjuwj1Rw4iUe8CCVBbDfsBzKMwzY3MhPQ_jgaggRLUbUYkVROC6IVfrGTI30BraxydEU3zLKIm55LTHGulP06wJYE9GXvNQXkJaPy-aYSc5e7cVE-OprtUtlI/' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  32:   
  33:  <a expr:href='&quot;http://www.google.com/bookmarks/mark?op=&quot; + &quot;add&amp;bkmk=&quot; + data:post.url + &quot;&amp;title=&quot; + data:post.title' target='_blank' title='Google Bookmark !'><img alt='Google Bookmark !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1b9DcMseWLBU7MRfCqq59jX3Q0rJpZv-ZsQt0f4EVzigjNee56LngQDZ54kKYd6wdbh1JAIT0GsjuE1BLbE5DYorU1uPylYCisKGddUrnPB6Bw8FqdBhYYd4-JewTAi9QgV0PSkjA7EU/' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  34:   
  35:  <a expr:href='&quot;http://www.printfriendly.com/print/v2?url=&quot; + data:post.url' target='_blank' title='Create PDF And Print Friendly !'><img alt='Create PDF And Print Friendly !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJd4eHcVAARNiMX1g4XFosuQ3dTcNoYH8q1RHTagXMs1oXY3j5o9GcqES2KgUyo6dFLca2LbOP94iNCdlopYjr9rJLIYGlDRLb5yTrWsKwWzKAd76MYHDn1OQZj3BtIEyUwpMmGC-AqOc/' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  36:   
  37:  <a expr:href='data:blog.homepageUrl + &quot;feeds/posts/default&quot;' target='_blank' title='Blog Feed !'><img alt='Blog Feed !' src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyzVfksL2mSuQoRh75q-7QWwic9Sm8zrEB8P5Uce9Q_aP734ably0ccu5PB3y6aDtMMAjVUdcLRH_zOgHW_EzbCXnkt0wfB9WGG6BdjnpW7JW54mKMMSfv7-uRpkpySyNqJbqKDW2kX0o/' style='width:16px; height:16px; padding:0; border:0; vertical-align:middle;'/></a> 
  38:   
  39:  </p> </span>

Save And Share :

Thuật toán sắp xếp mảng

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

namespace ConsoleApplication1
{
    class Question1
    {
        private int[] arrA;
        public string FindNumber(int n)
        {
            string result = "";
            try
            {
                int i;
                int j;
                int tmp;
                arrA = new int[n];
                for (i = 0; i < n; i++)
                {
                    Console.Write("\n\tNhap vao phan tu thu " + (i + 1)+": ");
                    arrA[i] = int.Parse(Console.ReadLine());
                }

                for (i = 0; i < n - 1; i++)
                {
                    for (j = i + 1; j < n; j++)
                    {
                        if (arrA[i] > arrA[j])
                        {
                            tmp = arrA[i];
                            arrA[i] = arrA[j];
                            arrA[j] = tmp;    //doi cho a[i] va a[j]
                        }
                    }                                    
                }
                // in ra mang da sap xep theo thu tu tang dan
                for (i = 0; i < n; i++)
                {                    
                    result += arrA[i]+" ";
                    //Sap xep giam dan
                    //result += arrA[n-(i+1)]+" ";
                }                
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }

    }
}

---------------------------------------------------------------------------------------

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Nhap so phan tu cua mang so nguyen:");
            int n = int.Parse(Console.ReadLine());

            Question1 q = new Question1();
            string result = q.FindNumber(n);
            Console.WriteLine("KET QUA SAP XEP TANG DAN: "+result);
            Console.ReadLine();
        }
    }
}

Cách 2

        /// <summary>

        /// Sorting an input array

        /// the output would be another array with sorted by ascending

        /// for example : input: 1,3,2 -> the output would be 1,2,3

        /// </summary>

        /// <param name="Str_ListBox">the input array</param>

        /// <returns>the output with sorted items</returns>

        public static string GetSortedArray(string sourceString)

        {

            List<int> lstSource = new List<int>();

            foreach (string s in sourceString.Split(','))

            {

                lstSource.Add(int.Parse(s));

            }

            lstSource.Sort();

            return ConvertListObjectToString(lstSource);

        }

Save And Share :

ASP.NET: Tạo bộ tìm kiếm gần đúng (tương đối) giống như tamtay.vn, google.com

Default.aspx

<form id="form1" runat="server">
    <div style="text-align: center">
        <span style="color: #ff6600"><strong>TÌM KIẾM TƯƠNG ĐỐI</strong></span><br />
        <span style="font-size: 10pt; font-family: Verdana">
        Nhập từ cần tìm:</span>
        <asp:TextBox ID="TextBox1" runat="server" Width="421px"></asp:TextBox>
        <asp:Button ID="btnSeach" runat="server" Text="Seach" OnClick="btnSeach_Click" /><br />
        <br />
        <hr />
        <asp:Label ID="lblSQL" Text="" runat="server"></asp:Label>
    </div>
    </form>

Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
/// Author: Trương Đức Tài
/// 09/11/2009 (dd/mm/yyy)
/// Phone: 0979.116118
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TimKiemGanDung.Utilities;

namespace TimKiemGanDung
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSeach_Click(object sender, EventArgs e)
        {
            string keyWord = TextBox1.Text;
            string sql = string.Empty;
               
            sql = SearchApproximate.ApproximateSearch(keyWord);
            lblSQL.Text = sql;

            // Khi có được chuỗi sql như trên các bạn biết phải làm gì rồi chứ?
            // Thanks!
        }
    }
}

SearchApproximate.cs

using System;
using System.Data;
using System.Configuration;
/// Author: Trương Đức Tài
/// 09/11/2009 (dd/mm/yyy)
/// Phone: 0979.116118
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

namespace TimKiemGanDung.Utilities
{
    public class SearchApproximate
    {
        // Phương thức trả về câu lệnh SQL dùng truy vấn dữ liệu
        public static string ApproximateSearch(string keyWord)
        {
            string sql = "SELECT * FROM Employer WHERE FullName LIKE ";
            return sql + "N'" + Exec(keyWord) + "' OR FullName LIKE N'" + Exec(ConvertVN.Convert(keyWord)) + "'";
        }

        // Phương thức chuyển đổi một chuỗi ký tự: Nếu chuỗi đó có ký tự " " sẽ thay thế bằng "%"
        public static string Exec(string keyWord)
        {
            string[] arrWord = keyWord.Split(' ');
            StringBuilder str = new StringBuilder("%");
            for (int i = 0; i < arrWord.Length; i++)
            {
                str.Append(arrWord[i] + "%");
            }
            return str.ToString();
        }
    }
}

ConvertVN.cs

/// Author: Trương Đức Tài
/// 09/11/2009 (dd/mm/yyy)
/// Phone: 0979.116118
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace TimKiemGanDung.Utilities
{
    public class ConvertVN
    {
        // Phương thức Convert một chuỗi ký tự Có dấu sang Không dấu
        public static string Convert(string chucodau)
        {
            const string FindText = "áàảãạâấầẩẫậăắằẳẵặđéèẻẽẹêếềểễệíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵÁÀẢÃẠÂẤẦẨẪẬĂẮẰẲẴẶĐÉÈẺẼẸÊẾỀỂỄỆÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴ";
            const string ReplText = "aaaaaaaaaaaaaaaaadeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyyAAAAAAAAAAAAAAAAADEEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOOOUUUUUUUUUUUYYYYY";
            int index = -1;
            char[] arrChar = FindText.ToCharArray();
            while ((index = chucodau.IndexOfAny(arrChar)) != -1)
            {
                int index2 = FindText.IndexOf(chucodau[index]);
                chucodau = chucodau.Replace(chucodau[index], ReplText[index2]);
            }
            return chucodau;
        }
    }
}

Mã nguồn tải tại đây

(Đã hoàn thành 99%, các bạn hãy chạy thử và hoàn thành tiếp bộ tìm kiếm với kết nối CSDL nhé)
Author: Trương Đức Tài

Save And Share :

Convert chữ tiếng việt có dấu thành không dấu C#

Hàm dùng để convert chữ tiếng việt có dấu thành chữ tiếng việt không dấu.

public static string ConvertVN(string chucodau)
    {
        const string FindText = "áàảãạâấầẩẫậăắằẳẵặđéèẻẽẹêếềểễệíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵÁÀẢÃẠÂẤẦẨẪẬĂẮẰẲẴẶĐÉÈẺẼẸÊẾỀỂỄỆÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴ";
        const string ReplText = "aaaaaaaaaaaaaaaaadeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyyAAAAAAAAAAAAAAAAADEEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOOOUUUUUUUUUUUYYYYY";
        int index = -1;
        char[] arrChar = FindText.ToCharArray();
        while ((index = chucodau.IndexOfAny(arrChar)) != -1)
        {
            int index2 = FindText.IndexOf(chucodau[index]);
            chucodau = chucodau.Replace(chucodau[index], ReplText[index2]);
        }
        return chucodau;
    } 

Save And Share :

Demo using CollectionBase (Set - Get fields in Struct or Object)

using System;
using System.Collections;
using System.Windows.Forms;

namespace WindowsApplication5
{
    public partial class Form1 : Form
    {
        Collection collection1 = new Collection();
        Collection collection2 = new Collection();

        public Form1()
        {
            InitializeComponent();
        }

        private void TurnIn_Click_1(object sender, EventArgs e)
        {
            // them vao collection
            collection1.Add(int.Parse(txtAge.Text), txtName.Text);
            lblStatus.Text = "Test " + txtAge.Text + " added.";
        }

        private void LookAt_Click_1(object sender, EventArgs e)
        {
            bool FirstCheck = collection2.Count() == 0;
            bool bThoat = false;

            while (collection1.Count() > 0 && !bThoat)
            {
                int x = collection1.Count() - 1;
                // copy phan tu cuoi cung cua collection1 thanh phan tu dau tien cua collection2
                collection2.Insert(collection1.GetID(x), collection1.GetName(x), 0);

                // xoa phan tu cuoi cung cua collection1
                collection1.RemoveAt(x);

                // kiem tra phan tu nay co la bai test dang tim
                if (collection2.GetID(0) == int.Parse(txtAge.Text))
                {
                    MessageBox.Show("Student Name is: " + collection2.GetName(0));
                    bThoat = true;
                }
            }

            if (!bThoat) // neu khong tim thay bai test nao
                if (FirstCheck)
                    MessageBox.Show("Test not found.");
                else
                    MessageBox.Show("Please click RETURN A TEST button to reset this result.");
        }        

        private void Return_Click_1(object sender, EventArgs e)
        {
            // chuyen tat ca phan tu cua collection2 vao lai collection1
            while (collection2.Count() > 0)
            {
                collection1.Add(collection2.GetID(0), collection2.GetName(0));
                collection2.RemoveAt(0);
            }
        }     
    }

    public class Collection : CollectionBase
    {
        public struct TuTao
        {
            public int Age;
            public string Name;
        }

        public void Add(int Age, string Name)
        {
            TuTao temp = new TuTao();
            temp.Age = Age;
            temp.Name = Name;
            InnerList.Add(temp);
        }

        public void RemoveAt(int Vitri)
        {
            InnerList.RemoveAt(Vitri);
        }

        public void Insert(int Age, string Name, int Vitri)
        {
            TuTao temp = new TuTao();
            temp.Age = Age;
            temp.Name = Name;
            InnerList.Insert(Vitri, temp);
        }

        public int Count()
        {
            return InnerList.Count;
        }

        public string GetName(int Vitri)
        {
            TuTao temp = (TuTao)InnerList[Vitri];
            return temp.Name;
        }

        public int GetID(int Vitri)
        {
            TuTao temp = (TuTao)InnerList[Vitri];
            return temp.Age;
        }
    }        
}

Demo 2

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

namespace CTDL_Chap01_Ex4
{
    class Program
    {
        static void Main(string[] args)
        {
            SinhVien A = new SinhVien();
            A.Add("Le Thanh Dat");
            A.Add("Vo Thuy Lien Tinh");
            A.Add("Nguyen Thi My Hanh");

            SinhVien B = new SinhVien();
            B.Add("http://www.vnxsoft.com");
            B.Add("http://www.microsoft.com");

            Console.WriteLine("Truoc khi swap:");
            for (int i = 0; i < A.Count(); i++)
                Console.WriteLine(A.GetName(i));
            Console.WriteLine();
            for (int i = 0; i < B.Count(); i++)
                Console.WriteLine(B.GetName(i));

            Swap<SinhVien>(ref A, ref B);

            Console.WriteLine("\r\n\r\nSau khi swap:");
            for (int i = 0; i < A.Count(); i++)
                Console.WriteLine(A.GetName(i));
            Console.WriteLine();
            for (int i = 0; i < B.Count(); i++)
                Console.WriteLine(B.GetName(i));

            Console.ReadLine();
        }

        public static void Swap<T>(ref T v1, ref T v2)
        {
            T temp = (T)v1;
            v1 = v2;
            v2 = temp;
        }
    }

    class SinhVien : CollectionBase
    {
        public void Add(object item)
        {
            InnerList.Add(item);
        }

        public string GetName(int Vitri)
        {
            return InnerList[Vitri].ToString();
        }

        public int Count()
        {
            return InnerList.Count;
        }
    }
}

Save And Share :

How to Post data in C# . NET HttpWebRequest

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;

namespace ConsoleApplication1
{
    class Class1
    {
        public string Post(string url, string postData)
        {
            string vystup = null;
            try
            {
                //Our postvars
                byte[] buffer = Encoding.ASCII.GetBytes(postData);
                //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)
            {
                Console.Write(ex.Message);
            }
            return vystup.Trim() + "\n";

        }
    }
}

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Class1 cls1 = new Class1();
            string sResponse = cls1.Post(@"http://test.webjet.com.au/webjettsatrial/unauth.aspx", @"PFPageID=FlightFinderTab&PFLayoutID=Layout&__EVENTTARGET=&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=%2FwEPDwUJNjEyNDMwODIwD2QWAgIBD2QWAgIJD2QWAmYPZBYCZg9kFgICBw9kFgJmD2QWEmYPDxYCHgdWaXNpYmxlaGQWAmYPZBYCZg9kFgICAw8PFgIeBFRleHQFAjMwZGQCAQ8PFgIfAGhkZAIEDxYCHwBoZAIGDw8WAh8AaGRkAgkPDxYCHwBoZGQCCg8PFgIfAGhkFgQCAQ8PFgIfAGhkZAIFDxYCHwEFDDEzMDAgMTM3IDczN2QCDA8WAh8AaGQCDQ8WAh8AaGQCDg8WAh8AaGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFhkFKENvbnRlbnRWaWV3JFBhZ2VMYXlvdXQkVG9wTmF2JGltZ1dlYk1haWwFJUNvbnRlbnRWaWV3JFBhZ2VMYXlvdXQkVG9wTmF2JEltZ0xvZ28FRkNvbnRlbnRWaWV3JFBhZ2VMYXlvdXQkRmxpZ2h0RmluZGVyVGFiJG1udVN1Yk5hdmlnYXRpb25Vc2MkaW1nTGVmdE1lbnUFVUNvbnRlbnRWaWV3JFBhZ2VMYXlvdXQkRmxpZ2h0RmluZGVyVGFiJEhvbWVwYWdlVGFicyRGbGlnaHRzVGFiJHBubFRyaXBUeXBlJFRyaXBUeXBlIzAFVUNvbnRlbnRWaWV3JFBhZ2VMYXlvdXQkRmxpZ2h0RmluZGVyVGFiJEhvbWVwYWdlVGFicyRGbGlnaHRzVGFiJHBubFRyaXBUeXBlJFRyaXBUeXBlIzEFVUNvbnRlbnRWaWV3JFBhZ2VMYXlvdXQkRmxpZ2h0RmluZGVyVGFiJEhvbWVwYWdlVGFicyRGbGlnaHRzVGFiJHBubFRyaXBUeXBlJFRyaXBUeXBlIzEFVUNvbnRlbnRWaWV3JFBhZ2VMYXlvdXQkRmxpZ2h0RmluZGVyVGFiJEhvbWVwYWdlVGFicyRGbGlnaHRzVGFiJHBubFRyaXBUeXBlJFRyaXBUeXBlIzIFVUNvbnRlbnRWaWV3JFBhZ2VMYXlvdXQkRmxpZ2h0RmluZGVyVGFiJEhvbWVwYWdlVGFicyRGbGlnaHRzVGFiJHBubFRyaXBUeXBlJFRyaXBUeXBlIzIFWkNvbnRlbnRWaWV3JFBhZ2VMYXlvdXQkRmxpZ2h0RmluZGVyVGFiJEhvbWVwYWdlVGFicyRGbGlnaHRzVGFiJGN0bERlc3RpbmF0aW9uRmluZGVyX2ZpbmRlcgVgQ29udGVudFZpZXckUGFnZUxheW91dCRGbGlnaHRGaW5kZXJUYWIkSG9tZXBhZ2VUYWJzJEZsaWdodHNUYWIkY3RsRGVzdGluYXRpb25GaW5kZXJfZmluZGVyQm90dG9tBUhDb250ZW50VmlldyRQYWdlTGF5b3V0JEZsaWdodEZpbmRlclRhYiRIb21lcGFnZVRhYnMkRmxpZ2h0c1RhYiRidG5TZWFyY2gFUUNvbnRlbnRWaWV3JFBhZ2VMYXlvdXQkRmxpZ2h0RmluZGVyVGFiJEhvbWVwYWdlVGFicyRDYXJzVGFiMSRjdGxQaWNrdXBDaXR5X2ZpbmRlcgVXQ29udGVudFZpZXckUGFnZUxheW91dCRGbGlnaHRGaW5kZXJUYWIkSG9tZXBhZ2VUYWJzJENhcnNUYWIxJGN0bFBpY2t1cENpdHlfZmluZGVyQm90dG9tBUxDb250ZW50VmlldyRQYWdlTGF5b3V0JEZsaWdodEZpbmRlclRhYiRIb21lcGFnZVRhYnMkQ2Fyc1RhYjEkY2JsQ2FyVmVuZG9ycyQwBUxDb250ZW50VmlldyRQYWdlTGF5b3V0JEZsaWdodEZpbmRlclRhYiRIb21lcGFnZVRhYnMkQ2Fyc1RhYjEkY2JsQ2FyVmVuZG9ycyQxBUxDb250ZW50VmlldyRQYWdlTGF5b3V0JEZsaWdodEZpbmRlclRhYiRIb21lcGFnZVRhYnMkQ2Fyc1RhYjEkY2JsQ2FyVmVuZG9ycyQyBUxDb250ZW50VmlldyRQYWdlTGF5b3V0JEZsaWdodEZpbmRlclRhYiRIb21lcGFnZVRhYnMkQ2Fyc1RhYjEkY2JsQ2FyVmVuZG9ycyQzBUxDb250ZW50VmlldyRQYWdlTGF5b3V0JEZsaWdodEZpbmRlclRhYiRIb21lcGFnZVRhYnMkQ2Fyc1RhYjEkY2JsQ2FyVmVuZG9ycyQ0BUxDb250ZW50VmlldyRQYWdlTGF5b3V0JEZsaWdodEZpbmRlclRhYiRIb21lcGFnZVRhYnMkQ2Fyc1RhYjEkY2JsQ2FyVmVuZG9ycyQ0BUZDb250ZW50VmlldyRQYWdlTGF5b3V0JEZsaWdodEZpbmRlclRhYiRIb21lcGFnZVRhYnMkQ2Fyc1RhYjEkYnRuU2VhcmNoBUhDb250ZW50VmlldyRQYWdlTGF5b3V0JEZsaWdodEZpbmRlclRhYiRIb21lcGFnZVRhYnMkSG90ZWxzVGFiMSRidG5TZWFyY2gFOkNvbnRlbnRWaWV3JFBhZ2VMYXlvdXQkRmxpZ2h0RmluZGVyVGFiJGJ0blNlYXJjaE1hdHJpeERvd24FMkNvbnRlbnRWaWV3JFBhZ2VMYXlvdXQkQm90dG9tTmF2JGJ0blByb2ZpbGVEZXRhaWxzBSlDb250ZW50VmlldyRQYWdlTGF5b3V0JEJvdHRvbU5hdiRidG5Mb2dvbgUpQ29udGVudFZpZXckUGFnZUxheW91dCRSaWdodE5hdiRidG5NeVRyaXAHB4SN%2BrUIjKsA31wzEsFFOrcfag%3D%3D&__PREVIOUSPAGE=oyjS_uJrr0APVQWbsJUmfEUfPFMytN5uT70VAkQkkzA1&TSAServerName=&TSALastClientIP=&mail=Enter+your+email+address&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24pnlTripType%24TripType=Return&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24ctlDeparting=SYD&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24ctlDestinationFinder_city=London+Area+Airports&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24ctlDestinationFinder_cityCode=&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24ctlTravelClass=ECONOMY&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24ctlDepartureDate_day=10&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24ctlDepartureDate_month=2010%2F09&ctlDepartureDate_selectedYear=2010&ctlDepartureDate_selectedMonth=9&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24ctlReturnDate_day=20&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24ctlReturnDate_month=2010%2F09&ctlReturnDate_selectedYear=2010&ctlReturnDate_selectedMonth=9&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24ctlAirline1=0&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24ctlAirline2Hidden=0&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24uscNumberOfPassengers%24ctlAdults=1&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24uscNumberOfPassengers%24ctlChildren=0&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24uscNumberOfPassengers%24ctlInfants=0&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24SearchTodayTime=18&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24ctlPickupCity_city=&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24ctlPickupCity_cityCode=&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24ctlPickupDate_day=3&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24ctlPickupDate_month=2010%2F08&ctlPickupDate_selectedYear=2010&ctlPickupDate_selectedMonth=8&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24ctlPickupTime=%3F&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24ctlPickupLocation=NotSpecified&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24ctlDropoffDate_day=4&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24ctlDropoffDate_month=2010%2F08&ctlDropoffDate_selectedYear=2010&ctlDropoffDate_selectedMonth=8&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24ctlDropoffTime=%3F&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24ctlDropoffLocation=NotSpecified&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24ctlCarSize=Any&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24cblCarVendors%240=on&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24cblCarVendors%241=on&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24cblCarVendors%242=on&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24cblCarVendors%243=on&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24CarsTab1%24cblCarVendors%244=on&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24HotelsTab1%24HotelDestination%24Countries=AU&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24HotelsTab1%24HotelDestination%24Destinations=451&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24HotelsTab1%24HotelDestination%24Locations=&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24HotelsTab1%24HotelDestination%24CascadingDropDown1_ClientState=AU%3A%3A%3AAustralia&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24HotelsTab1%24HotelDestination%24ccdCountryDestination_ClientState=451%3A%3A%3ASydney&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24HotelsTab1%24HotelDestination%24ccdDestinationLocation_ClientState=%3A%3A%3A&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24HotelsTab1%24ctlCheckInDate_day=2&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24HotelsTab1%24ctlCheckInDate_month=2010%2F08&ctlCheckInDate_selectedYear=2010&ctlCheckInDate_selectedMonth=8&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24HotelsTab1%24ctlCheckOutDate_day=3&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24HotelsTab1%24ctlCheckOutDate_month=2010%2F08&ctlCheckOutDate_selectedYear=2010&ctlCheckOutDate_selectedMonth=8&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24HotelsTab1%24ctlNumberOfAdults=1&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24HotelsTab1%24ctlNumberOfChildren=0&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24HotelsTab1%24rblResultsViewMode=List&ContentView%24PageLayout%24FlightFinderTab%24currentView=SEARCH&Question=&QuestionLOH=&hiddenInputToUpdateATBuffer_CommonToolkitScripts=0&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24btnSearch.x=0&ContentView%24PageLayout%24FlightFinderTab%24HomepageTabs%24FlightsTab%24btnSearch.y=0");

            Console.WriteLine(sResponse);
            Console.ReadLine();
        }
    }
}

Lưu ý để lấy dữ liệu từ Post dạng string dùng tool: Fiddler Web Debugger(v2.2.9.1) ,
sau đó truyền string đó vào phương thức Post trong Class1 -> public string Post(string url, string postData)

Save And Share :

Index trong MS SQL SERVER

Nonclustered khác Clustered ở chỗ trong 1 table có lượng dữ liệu lớn với hàng ngàn, hàng triệu record thì khi tạo Clustered Index nó sẽ sắp xếp dữ liệu giúp chúng ta truy xuất nhanh hơn. Còn Nonclustered thì ko. Trong 1 table bạn chỉ có thể tạo 1 Clustered và nhiều Nonclustered, cho nên khi bạn tạo table và xác định PK thì PK đó được mặc định là Clustered. Vì thế khi bạn tạo thêm 1 Clustered Index cho table đó thì nó sẽ báo lỗi.


Index, hay "chỉ mục" thực chất là một dạng tương tự như phần mục lục của một cuốn sách hay của một cuốn từ điễn vậy, các giá trị trong bảng được sắp theo cột, như vậy với suy nghĩ trên thì nếu cột nào được sắp index thì các giá trị trong cột đó sẽ được sắp xếp trong một cấu trúc bảng trong theo một trật tự dựa vào dữ liệu của bảng đó, việc làm này chủ yếu là giúp cho việc truy xuất trở nên nhanh hơn. Điều này tương tự như khi bạn tra từ điễn, thử tưởng tượng khi từ điễn không sắp xếp các từ theo thứ tự như: A--->AA--->AB.... thì bạn sẽ mất bao lâu để tra một từ

.
Trong SQL, index đóng vai trò là tăng tốc truy xuất, do truy xuất cũng giống như khi bạn tra từ điễn, HT cần tìm kiếm thông tin trong hàng ngàn dữ liệu nên việc sắp xếp là cần thiết, mặt khác, do việc sắp xếp các dữ liệu là duy nhất (như trong từ điễn không thể có hai từ như nhau vì như vậy rất khó sắp xếp) nên có thể cho rằng index cũng tăng tính duy nhất trong CSDL. Và cuỗi cùng, như đã biết các câu lệnh JOIN, ORDER BY, GROUP BYcũng yêu cầu việc truy xuất dữ liệu liên tục nên index đồng thời cũng tăng tốc cho việc này.
Nghe có vẽ Index thật hữu dụng, nhưng khoan, index cũng có nhược điểm, cụ thể là để có index, bạn cần tạo nó, mà việc này rất tốn thời gian, đối với các project mà chúng ta làm thì chả thấy gì, nhưng nếu đó là một CSDL lớn thì việc này là cực kì lâu. Thứ hai, do index là tạo một cấu trúc bảng trong nên việc này gây tốn tài nguyên (nếu ai có cài google search desktop sẽ biết điều này). Và cuối cùng, do index là sắp xếp các dữ liệu nên nếu có sự thay đổi thì index cũng được update theo.


Index trong CSDL có hai loại: Clustered IndexNon-Clustered Index.


Clustered index: thường được tự tạo ra khi bảng có primary key do primary key đã duy trì độ duy nhất dữ liệu của cột, nên có thể nói clustered index chính là unique index. Trong clustered index, các dữ liệu ở cấu trúc bảng trong được sắp xếp một cách vật lý, tức là trong clustered index, dữ liệu bảng trong được sắp xếp đúng theo thư mục cây dựa vào bảng chữ cái. Cách làm việc của index là dựa trên ROOT PAGE, khi cần truy xuất, HT sẽ tìm đến địa chỉ cần tìm trong bảng SYSINDEXES. Ví dụ như trong Root page có hai cột, một cột chứa dữ liệu trong cột index cột còn lại chứa tham chiếu số trang(dòng) trong bảng, cột index có giá trị là A (tham chiếu trang bảng trong là 1) và D(tham chiếu trang bảng trong là 2), (việc này do index quyết định), bạn cần tìm "C", như vậy theo hệ chữ cái, HT sẽ biết rằng là C trong khoảng giữa A và D, HT từ đó dò đến trang bảng trong thứ 1 (tức chứa kí tự A, B, C .như vậy tương tự trang 2 sẽ là D,E,F...). Trong trang thứ 1, HT tiếp tục dò tìm kí tự C, lúc này kí tự C tham chiếu trang bảng thật là dòng 3 chẳng hạn. từ đó, HT lại lần đến trang bảng thật dòng 3 và dữ liệu được truy xuất (quá trình trên có thể tiếp tục nếu dữ liệu nhiều). trong một bảng CHỈ được có duy nhất một clustered index

Non-Clustered Index: khác với clustered Index, non-Clustered Index không sắp xếp dữ liệu theo một trật tự vật lý như clustered mà là "loạn xà ngầu" trong bảng thông tin, miễn sao nó nằm trong một logic do index qui định :D. trong một bảng có thể chứa đến 249 non-clustered index. còn cách hoạt động thì tương tự clustered index, có khác là khi truy xuất đến bảng thông tin cuối thì thông tin không được sắp xếp theo trật tự thôi ví dụ như A--->C---->B----->E---->D.....
một bảng không có index gọi là HEAP.
mặc định thì primary key là clustered index còn foreign key là non-clustered index, do đó non-clustered index mặc định không đẩy mạnh tính duy nhất dữ liệu.
trong thực hành, để xác định clustered index, thường thì đó là primary key, nếu bảng có khóa composite thì index tự tạo cho cột khóa nào có dữ liệu dễ sắp xếp hơn. Nói chung thì clustered index thường không cần ta can thiệp, riêng non-clustered index thì khác, trước hết cần biết CSDL dùng để làm gì, từ đó xác định dữ liệu cột nào thường dùng để tìm kiếm trong các querry. Ở đây chủ yếu là các cột trong câu lệnh điều WHERE, ORDER BY, GROUP BY, hay các foreign key trong querry yêu cầu JOIN thì bạn có thể yên tâm "phán" cho nó cái non-clustered index rồi :D

Save And Share :

 
  • Followers