9/16/2012

Demo Code

 public static bool IsValidURL(string strURL)
{
    string regExPattern = @"^^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_=]*)?$";
    Regex re = new Regex(regExPattern);
    return re.IsMatch(strURL);
}
demo highlight foo bar

 

Demo Quote

Save And Share :

8/25/2012

Easy Change the Text Selection Color In Blogger

It very simple to change your select sentence or a single word prevent by default with set as blue color. Now let's start:

1.  Go to Blogger Dashboard > Template > Edit HTML.
2.  Back up your template first if you don't want make some problem :)
3.  Check the Expand Widget Templates checkbox.
4.  Now search (CTRL+F) for the code tag below:
 ]]></b:skin>
And now add the below code before it
::-moz-selection{background: #9E0ADC;color: white;}
::selection{background: #9E0ADC;color: white;}
You can see demo on my blog. Hope you enjoyed doing this trick for your blog. 

Save And Share :

6/11/2012

Regex quick reference

[abc] A single character of: a, b or c
[^abc] Any single character except: a, b, or c
[a-z] Any single character in the range a-z
[a-zA-Z] Any single character in the range a-z or A-Z
^ Start of line
$ End of line
\A Start of string
\z End of string
. Any single character
\s Any whitespace character
\S Any non-whitespace character
\d Any digit
\D Any non-digit
\w Any word character (letter, number, underscore)
\W Any non-word character
\b Any word boundary character
(...) Capture everything enclosed
(a|b) a or b
a? Zero or one of a
a* Zero or more of a
a+ One or more of a
a{3} Exactly 3 of a
a{3,} 3 or more of a
a{3,6} Between 3 and 6 of a

options: i case insensitive m make dot match newlines x ignore whitespace in regex o perform #{...} substitutions only once

Save And Share :

Remove Html Tag in C#

You want to remove HTML tags from your string. This is useful for displaying HTML in plain text and stripping formatting like bold and italics, while not removing any actual textual content. Test the methods available for this functionality for performance and correctness with test cases.

These C# example programs show how to remove HTML tags from strings.

Removing HTML tags from strings

Input:    <p>The <b>dog</b> is <i>cute</i>.</p>
Output:   The dog is cute.

Performance test for HTML removal

HtmlRemoval.StripTagsRegex:         2404 ms
HtmlRemoval.StripTagsRegexCompiled: 1366 ms
HtmlRemoval.StripTagsCharArray:      287 ms [fastest]

File length test for HTML removal

File tested:                        Real-world HTML file
File length before:                 8085 chars
HtmlRemoval.StripTagsRegex:         4382 chars
HtmlRemoval.StripTagsRegexCompiled: 4382 chars
HtmlRemoval.StripTagsCharArray:     4382 chars

Examples

First, here is a static class that tests three different ways of removing HTML tags and their contents. The methods receive string arguments and then process the string and return new strings that do not have the HTML tags. The methods have different performance characteristics. As a reminder, HTML tags start with < and end with >.

HtmlRemoval static class [C#]

using System;
using System.Text.RegularExpressions;

/// <summary>
/// Methods to remove HTML from strings.
/// </summary>
public static class HtmlRemoval
{
    /// <summary>
    /// Remove HTML from string with Regex.
    /// </summary>
    public static string StripTagsRegex(string source)
    {
	return Regex.Replace(source, "<.*?>", string.Empty);
    }

    /// <summary>
    /// Compiled regular expression for performance.
    /// </summary>
    static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);

    /// <summary>
    /// Remove HTML from string with compiled Regex.
    /// </summary>
    public static string StripTagsRegexCompiled(string source)
    {
	return _htmlRegex.Replace(source, string.Empty);
    }

    /// <summary>
    /// Remove HTML tags from string using char array.
    /// </summary>
    public static string StripTagsCharArray(string source)
    {
	char[] array = new char[source.Length];
	int arrayIndex = 0;
	bool inside = false;

	for (int i = 0; i < source.Length; i++)
	{
	    char let = source[i];
	    if (let == '<')
	    {
		inside = true;
		continue;
	    }
	    if (let == '>')
	    {
		inside = false;
		continue;
	    }
	    if (!inside)
	    {
		array[arrayIndex] = let;
		arrayIndex++;
	    }
	}
	return new string(array, 0, arrayIndex);
    }
}

Notes. This is a public static class written in the C# language that does not save state. You can call into the class using the code HtmlRemoval.StripTags*. Normally, you can put this class in a separate file named HtmlRemoval.cs. Because it is not project-specific, it is useful for many programs.

StripTagsRegex. This method uses a static call to Regex.Replace, and therefore the expression is not compiled. For this reason, this method could be optimized by pulling the Regex out of the method, such as in the second method. The regular expression specifies that all sequences matching < and > with any number of characters, but the minimal number, are replaced with string.Empty (removed).

StripTagsRegexCompiled. This method does the exact same thing as the previous method, but its regular expression is pulled out of the method call and stored in the static class. I recommend this method for most programs, as it is very simple to inspect and considerably faster than the first method. The static Regex will only be created once in your program.

StripTagsCharArray. This method is a heavily optimized version of an approach that could instead use StringBuilder. In most benchmarks, this method is faster and is appropriate for when you need to strip lots of HTML files. A detailed description of the method's body is available below.

Tests

Here we look at a program that runs these methods through a very simple test. The three methods work identically on valid HTML. One thing you should note is that the char array method will strip anything that follows a <, but the Regex methods will require a > before they strip the tag.

Program that tests HTML removal [C#]

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
	const string html = "<p>There was a <b>.NET</b> programmer " +
	    "and he stripped the <i>HTML</i> tags.</p>";

	Console.WriteLine(HtmlRemoval.StripTagsRegex(html));
	Console.WriteLine(HtmlRemoval.StripTagsRegexCompiled(html));
	Console.WriteLine(HtmlRemoval.StripTagsCharArray(html));
    }
}

Output

There was a .NET programmer and he stripped the HTML tags.
There was a .NET programmer and he stripped the HTML tags.
There was a .NET programmer and he stripped the HTML tags.

 

First, from my performance research I know regular expressions in the C# language are usually not the fastest way to process test. I wrote an algorithm that uses a combination of char arrays and the new string constructor to strip HTML tags, filling the requirement and often performing better.

The benchmark for these methods stripped 10000 HTML files of around 8000 characters in tight loops. The file was read in from File.ReadAllText. The result was that the char array method was considerably faster. This could worthwhile to use if you have to strip many files in a script, such as one that preprocesses a large website in memory.

Iterative method

The method here that uses char arrays and is dramatically faster than the other two methods uses a neat algorithm for parsing the HTML quickly. It iterates through all characters, flipping a flag Boolean depending on whether it is inside a tag block. It only adds characters to the array buffer if it is not a tag. For performance, it uses char arrays and the new string constructor that accepts a char array and a range. This is faster than using StringBuilder.

Using RegexOptions.Compiled and a separate Regex results in better performance than using the Regex static method. RegexOptions.Compiled has some drawbacks, however. It can reduce startup time by 10x in some cases. More material is available pertaining to make Regexes simpler and faster to run.

Self-closing tags

In XHTML, certain elements such as BR and IMG have no separate closing tag, and instead use the "/>" at the end of the first tag. The test file noted includes these self-closing tags, and the methods handle it correctly. Here are some HTML tags supported.

Supported tags

<img src="" />
<img src=""/>
<br />
<br/>
< div >
<!-- -->

Source: dotnetperls.com

See some example:

How to remove Html Tag form Client site with jQuery

Save And Share :

Remove Html Tag with jQuery

The example below show how to remove HTML tags from strings with jQuery

 

INPUT:         <b>We</b>love<span>jQuery.</span>

OUTPUT:   We love jQuery.

jQuery source:

var NewString = OriginalString.replace(/(<([^>]+)>)/ig, "");

Thumbs up

Save And Share :

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 :

 
  • Followers