Showing posts with label Hack. Show all posts
Showing posts with label Hack. Show all posts

Thursday, December 21, 2006

Features or improvment that ASP.NET 3.0 should have !

1, All the places having XSS vulnerabilities (relating to text), the controls should have a properties that like the Literal contrl's Mode property to check tis vulnerabilities.

Sercurity Alerst:

  1. By default, populating the TableCell control with data from untrusted sources can create XSS vulnerabilities.
  2. By default, populating the Literal control with data from untrusted sources can create Cross Site Scripting (XSS) vulnerabilities. Set the Mode property to Encode to provide HTML encoding of untrusted data that will be placed into the Text property.
  3. Populating the Label control with data from an untrusted source can create Cross Site Scripting (XSS) vulnerabilities.
  4. Populating the CheckBox control’s Text property with data from an untrusted source can create Cross Site Scripting (XSS) vulnerabilities.
  5. Populating the RadioButton control’s Text property with data from an untrusted source can create Cross Site Scripting (XSS) vulnerabilities.

Be sure to HTML encode all data using either the Server.HtmlEncode or the HttpUtility.HtmlEncode method.

The Literal Server Contrl of ASP.NET 2.0

The best use for the Literal control is in scenarios where you want to render text and controls directly into a page without any additional markup.

The Literal control contains the Mode property, which is used to specify particular handling of the content of the Text property:

Mode : Description
PassThrough : The Text content is rendered as is.
Encode : The Text content is HTML-encoded.
Transform : The Text content is converted to match the markup languageof the requesting browser, such as HTML, XHTML, WML, or cHTML. If the markup language is HTML or XHTML, the content is passed through to the browser.

Security Alert:
By default, populating the Literal control with data from untrusted sources can create Cross Site Scripting (XSS) vulnerabilities. Set the Mode property to Encode to provide HTML encoding of untrusted data that will be placed into the Text property.

The Server object of ASP.NET / HttpServerUtility




The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided by ASP.NET.

HttpServerUtility provides helper methods for processing Web requests.

The HtmlEncode method helps ensure that any user-supplied string input will be rendered as static text in browsers instead of executable script code or interpreted HTML elements.

The UrlEncode method encodes URLs so that they are correctly transmitted in the HTTP stream.

For examples:



The HttpUtility class exposes methods for encoding and decoding string based URLs, URL tokens, and paths. The HttpUtility is used internally by the HttpServerUtility class.
Additionally, the HttpUtility class contains encoding and decoding utility methods that are not accessible from the Server.

The following code example demonstrates the use of the UrlEncode, UrlDecode), and ParseQueryString methods of the HttpUtility class.


Tuesday, December 19, 2006

Determining the Number of Days in a Month with Javascript

Scenario : 判断给定的某年某月有多少天

Essentially, writing some code to determine the number of days in a given month of a given year with javascript is not the worlds most difficult task. The solution normally involves determining if the month is February, an month with 30 days or a month with 31 days, then (if February) checking if the year is a leap year. All these tests add up, however, and add several lines of code to your .js file.

They are unnecessary! Apparently, the javascript Date function allows you to overflow the day number parameter that you pass, creating a date in the next month. Deliberately overflowing the day parameter and checking how far the resulting date overlaps into the next month is a quick way to tell how many days there were in the queried month. Here is a function that does this:

function daysInMonth(iMonth, iYear) {
return 32 - new Date(iYear, iMonth, 32).getDate();
}

iMonth is zero based, so 0 represents January, 1 represents February, 2 represents March and 11 represents December.
iYear is not zero based, this is the actual calendar year number. (2006 is actually 2006)


How does this function work? It is quite simple. When the Date() function is given a day number that is greater than the number of days in the given month of the given year, it wraps the date into the next month. The getDate() function returns the day of the month, starting from the beginning of the month that the date is in. So, day 32 of March is considered to be day 1 of April. Subtracting 1 from 32 gives the correct number of days in March!


Pray that the browser developers know the correct way to determine whether a year is a leap year! (It's more complicated than a simple mod 4 == 0) Here is a quote from Wikipedia's page on leap years: "The Gregorian calendar, the current standard calendar in most of the world, adds a 29th day to February in all years evenly divisible by 4, except for centennial years (those ending in '00'), which receive the extra day only if they are evenly divisible by 400. Thus 1600, 2000 and 2400 are leap years but 1700, 1800, 1900 and 2100 are not."

Monday, October 30, 2006

Thursday, October 26, 2006

Using CheckBoxList in ASP.NET

e .NET Framework Class Library CheckBoxList Members

Sunday, October 22, 2006

Using unmanaged code

^ What is Interoperation for?
There might be many lines of legacy code left for companies. If they had to rewrite and retest thiese codes prior to launching any new application developed in .NET, they would have never made the switch. Using an "all or nothing" approach with migrating to .NET is simply too expensive and time consuming for many companies with investments in legacy code.
By taking advantage of Interoperation, they are able to migrate their existing applications little by little, in a manner that was virtually transparent to clients. Were it not for Interoperation, they would have never made the migration.


^ Prior to advent of the .NET Framework, the COM Framework was the primary framework for developers to interact with the Windows operating system.

d The mechanism that serves as proxy so that the .NET runtime can communicate with a COM component is known as a Runtime Callable Wrapper (RCW), which handles the majority of the work between .NET and COM for you, including marshaling data types, handling events, and handling interfaces.

d Unlike pure .NET components, COM components must be registered before they can be used.
d Every COM components must have an entry in the Windows registry.

d After importing it, using an object contained in a given COM library is virtually identical to using ne created purely in .NET.

d What is Platform Invoke? and when to use it?

d Use Platform Invoke through the System.Runtime.InteropServices namespace:


  1. Create a static/shared external method with the name of the function you want to call.
  2. Decorate it with the DllImport attribute specifying the library that it should call.
  3. Call the method from your code.

Imports System.Runtime.InteropServices
Public Class InterExample


Private Shared Function GetForeWindow() As IntPtr
End Function

Public Shared Sub GetScreenDemo()
Dim DemoHandle = GetForeWindow()
End Sub

End Class
d Encapsulating DLL Functions: Because Platform Invoke calls is not elegant, it's often beneficial to create a class that exposes them and wraps this functionality. After all, much of the .NET Framework is composed of precisely this methodology.
@ You need to call an unmanaged function from your managed code by using Platform Invoke services. What should you do?
Create a class to hold DLL functions and then create prototype methods by using managed code.
 

Sunday, October 15, 2006

Resizing & Scaling images in .NET


e 4GuysFromRolla Scott Mitchell Displaying a List of Scaled Images
e 4GuysFromRolla Scott Mitchell True Image Resizing, Part 1
e 4GuysFromRolla Scott Mitchell True Image Resizing, Part 2 : About thumbnail

e SmartThumbnail.Net Component

Implementing CAPTCHA in ASP.NET

e CAPTCHA Image
e Generating ASP.NET Images on the Fly

How to display HTML/XML tags code in webpage?

Method 1: Use the <xmp>tage to surround the HTML or XML code to be displayed as plain text. For example:

<xmp>system><display><name>Someone</name></display></system>

Method 2: Convert the <> to &lt;>.
To display a simple link as code: &lt;a href="http://www.simplelink.com&quot;>Here</a>
Would show as : <a href="http://www.simplelink.com">Here</a>

@ Simple Code Encoder SUPER great tool, i.e.
<system.web>
      <urlMappings enabled="true">
            <add url="~/About.aspx" mappedUrl="~/Site_Common/About.aspx"/>
            <add url="~/Legal.aspx" mappedUrl="~/Site_common/Legal.aspx"/>
      </urlMappings>
</system.web>


e Display Code In Entries

Saturday, October 14, 2006

URL Mapping in ASP.NET 2.0

When URL mapping is useful?
URL mapping comes handy in number of situations:

  • You want to hide a big URL from the end user and present an easy to remember shorter URL
  • You want to pass query string parameters to a page but do not want them to be displayed to the user
  • You have changed web form names after the application is deployed
    How this works?

In ASP.NET 2.0 there is a configuration section called urlMappings that maps one URL to the other. The following markup shows how this section can be used:


<br /><system.web><br /><urlmappings enabled="true"><br /><add mappedurl="~/Site_Common/About.aspx" url="~/About.aspx"><br /><add mappedurl="~/Site_common/Legal.aspx" url="~/Legal.aspx"><br /></urlmappings><br /></system.web><br />

The enabled attribute of section enables or disables the URL mapping feature.
The sub section allows you to specify the actual mapping.
The url attribute of section specifies the URL as seen by the end user. It can be from browser address bar, hyper link or Response.Redirect statements.
The mappedUrl attribute species the URL that is actually served in place of the URL specified by url attribute.

You can specify as many URL mappings as you wish using multiple tags.

Friday, October 13, 2006

SQL Subqueries

INSERT INTO TableA (PosID, PosValue, DataDate) SELECT PosID, PosValue, DataDate FROM TableB WHERE DataDate = '2006-10-6' AND PosID = 'TAEE1'

^ Values (A,B,C)部分替换成一个SELECT A,B,C语句便可。


UPDATE TableA SET PosValue = (SELECT PosValue FROM TableB WHERE
DataDate = '2006-10-6' AND PosID = 'TAEE1' ) WHERE PosID = 'TAEE1' AND DataDate = '2006-10-6'


^
SELECT OUID, (SELECT ID, OUName FROM Accounts_OU WHERE ID = A.OUID ORDER BY ID) AS OUName FROM BizMgtStationOrder A WHERE PipeLineID = " & XXX & " ORDER BY OUID"


d Subquery Fundamentals

A subquery is a SELECT query that returns a single value and is nested inside a SELECT, INSERT, UPDATE, or DELETE statement, or inside another subquery. A subquery can be used anywhere an expression is allowed. In this example a subquery is used as a column expression named MaxUnitPrice in a SELECT statement.

SELECT Ord.OrderID, Ord.OrderDate,
(SELECT MAX(OrdDet.UnitPrice)
FROM Northwind.dbo.[Order Details] AS OrdDet
WHERE Ord.OrderID = OrdDet.OrderID) AS MaxUnitPrice
FROM Northwind.dbo.Orders AS Ord

A subquery is also called an inner query or inner select, while the statement containing a subquery is also called an outer query or outer select.

Many Transact-SQL statements that include subqueries can be alternatively formulated as joins. Other questions can be posed only with subqueries. In Transact-SQL, there is usually no performance difference between a statement that includes a subquery and a semantically equivalent version that does not. However, in some cases where existence must be checked, a join yields better performance. Otherwise, the nested query must be processed for each result of the outer query to ensure elimination of duplicates. In such cases, a join approach would yield better results. This is an example showing both a subquery SELECT and a join SELECT that return the same result set:

/* SELECT statement built using a subquery. */
SELECT ProductName
FROM Northwind.dbo.Products
WHERE UnitPrice =
(SELECT UnitPrice
FROM Northwind.dbo.Products
WHERE ProductName = 'Sir Rodney''s Scones')

/* SELECT statement built using a join that returns
the same result set. */
SELECT Prd1.ProductName
FROM Northwind.dbo.Products AS Prd1
JOIN Northwind.dbo.Products AS Prd2
ON (Prd1.UnitPrice = Prd2.UnitPrice)
WHERE Prd2.ProductName = 'Sir Rodney''s Scones'

A subquery nested in the outer SELECT statement has the following components:
A regular SELECT query including the regular select list components.
A regular FROM clause including one or more table or view names .
An optional WHERE clause.
An optional GROUP BY clause.
An optional HAVING clause.

The SELECT query of a subquery is always enclosed in parentheses. It cannot include a COMPUTE or FOR BROWSE clause, and may only include an ORDER BY clause when a TOP clause is also specified.

A subquery can be nested inside the WHERE or HAVING clause of an outer SELECT, INSERT, UPDATE, or DELETE statement, or inside another subquery. Up to 32 levels of nesting is possible, although the limit varies based on available memory and the complexity of other expressions in the query. Individual queries may not support nesting up to 32 levels. A subquery can appear anywhere an expression can be used, if it returns a single value.
If a table appears only in a subquery and not in the outer query, then columns from that table cannot be included in the output (the select list of the outer query).

Statements that include a subquery usually take one of these formats:


WHERE expression [NOT] IN (subquery)
WHERE expression comparison_operator [ANY ALL] (subquery)
WHERE [NOT] EXISTS (subquery)

In some Transact-SQL statements, the subquery can be evaluated as if it were an independent query. Conceptually, the subquery results are substituted into the outer query (although this is not necessarily how Microsoft® SQL Server™ actually processes Transact-SQL statements with subqueries).
There are three basic types of subqueries, those that:
Operate on lists, introduced with IN or those that a comparison operator modified by ANY or ALL.
Are introduced with an unmodified comparison operator and must return a single value.
Are existence tests introduced with EXISTS.


Wednesday, October 11, 2006

Label and Label Cloud / Tag and Tag Cloud

Making and sending HTML email

@ The Process of Creating and Sending an E-mail Message: To create and send an e-mail message, follow these steps:

  1. Create a MailMessage object. MailMessage and other mail-related classes are in the System.Net.Mail namespace.
  2. If you did not specify the recipients in the MailMessage constructor, add them to the MailMessage object.
  3. If you need to provide multiple views (such as plain text and HTML), create AlternateView objects and add them to the MailMessage object.
  4. If necessary, create one or more Attachment objects and add them to the MailMessage object.
  5. Create an SmtpClient object, and specify the SMTP server.
  6. If the SMTP server requires clients to authenticate, add credentials to the SmtpClient object.
  7. Pass your MailMessage object to the SmtpClient.Send method. Alternatively, you can use SmtpClient.SendAsync to send the message asynchronously.

How to create a MailMessage

^ 一定要首先创建空的MailMessage,然后把MailMessage.ToMailMessage.FromMailMessage.SubjectMailMessage.Body四个property依次添加到MailMessage中。还可以添加MailMessage.CcMailMessage.Bcc

^ 因为每次发送邮件不一定会发给多少个人,所以写程序时不区分发给单人还是多人的情况。把所有得到的收件人地址都放进一个MailAddressCollection中。

@ BCC stands for "blind carbon copy".

@ The problem with BCC is that spam filters frequently block messages that do not have the recipient's email address in the From header, Therefore, if you use BCC, the message will very likely be filtered.

How to create HTML email?

@ To create an HTML email message, supply HTML-tagged content for MailMessage.Body and set MailMessage.IsBodyHtml attribute to True.
Dim OneMailMessage = New MailMessage
String OneMailMessageHtmlBody = "XHTML codes ..."
OneMailMessage.IsBodyHtml = True
OneMailMessage.Body = OneMailMessageHtmlBody

@ Most email clients will ignore the head section, and will ignore any client-side scripts, and will not automatically download images from Web sites.

@ To embed images into an HTML message so that they appear when the user clicks the message (without requiring the user to explicitly choose to download images): first creat an HTML message using AlternateView and then add images using LinkedResource classes.

^ 因为有的邮件客户端或者服务器会阻止图片内容,或者只支持普通文本格式的邮件,或者用户设定只接受文本邮件,所以需要提供alternate view以根据情况显示邮件内容。

e 4guysfromrolla.com Sending Email in ASP.NET 2.0
e 4guysfromrolla.com Sending Email in ASP.NET 2.0: HTML-Formatted Emails, Attachments, and Gracefully Handling SMTP Exceptions

e Complete FAQ for the System.Net.Mail namespace found in .NET 2.0

Saturday, October 07, 2006

Page.IsPostBack

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'Page.IsPostBack是用来检查目前网页是否为第一次加载,
'当使用者第一次浏览这个网页时page.ispostback 会传回false,不是第一次浏览这个网页时就传回true;
'所以当我们在page_load 事件中就可以使用这个属性来避免做一些重复的动作。
'此处,如果是第一次加载,则要执行下列代码,否则就不执行,所以要保证If true Then
If Not Page.IsPostBack Then
......
End If
End Sub

Cross Page Postback in ASP.Net 2.0

Tuesday, October 03, 2006

ASP.NET Inline Data-Binding Syntax

@ One-way data binding:

Eval("", "")

第一部分是Item的名称;第二部分是一个Formatter。

@ Two-way data binding:
<%# Bind("Name", "{0:mm dd yyyy}") ) %>
第一部分是Item的名称;第二部分是一个Formatter。

Saturday, September 30, 2006

To collapse and hide a section of code in Visual Studio 2005

The #Region directive enables you to collapse and hide sections of code in Visual Basic files. The #Region directive lets you specify a block of code that you can expand or collapse when using the Visual Studio code editor. The ability to hide code selectively makes your files more manageable and easier to read. For more information, see How to: Outline and Hide Code.

#Region directives support code block semantics such as #If...#End If. This means they cannot begin in one block and end in another; the start and end must be in the same block. #Region directives are not supported within functions.

To collapse and hide a section of code
Place the section of code between the #Region and #End Region statements, as in the following example:

#Region "This is the code to be collapsed"
Private components As System.ComponentModel.Container
Dim WithEvents Form1 As System.Windows.Forms.Form

Private Sub InitializeComponent()
components = New System.ComponentModel.Container
Me.Text = "Form1"
End Sub
#End Region


The #Region block can be used multiple times in a code file; thus, users can define their own blocks of procedures and classes that can, in turn, be collapsed. #Region blocks can also be nested within other #Region blocks.

Note
Hiding code does not prevent it from being compiled and does not affect #If...#End If statements.

^ 在一个method范围内是不能使用Region的,如果要实现“收起放开”,需要使用CTRL+M and then CTRL+H以及CTRL+M and then CTRL+U.

@ Hide Selection
Collapses the currently selected text. Text must be selected to use this command. Shortcut keys are CTRL+M and then CTRL+H.

@ Stop Hiding Current
Removes the outlining information for the currently selected user-defined region. Shortcut keys are CTRL+M and then CTRL+U.
Note This command becomes available in Visual C# and Visual J# when Automatic Outlining is turned off or Stop Outlining is selected. Not available in Visual Basic.

Friday, September 29, 2006

Determining the Number of Days in a Month with Javascript

ATTENTION: The following words are quoted from great work of Mr. Charlie published at www.bigbold.com on Thu May 25 08:02:48 GMT 2006

Essentially, writing some code to determine the number of days in a given month of a given year with javascript is not the worlds most difficult task. It is the type of exercise that one would expect to be given as a newbie developer during a lab or lecture. The solution normally involves determining if the month is February, an month with 30 days or a month with 31 days, then (if February) checking if the year is a leap year. All these tests add up, however, and add several lines of code to your .js file. They are also unnecessary!

Apparently, the javascript Date function allows you to overflow the day number parameter that you pass, creating a date in the next month. Deliberately overflowing the day parameter and checking how far the resulting date overlaps into the next month is a quick way to tell how many days there were in the queried month. Here is a function that does this:

function daysInMonth(iYear, iMonth) {
return (32 - new Date(iYear, iMonth, 32).getDate());
}


N.B.: iMonth is zero based, so 0 represents January, 1 represents February, 2 represents March and 11 represents December. iYear is not zero based, this is the actual calendar year number. (2006 is actually 2006)

Pray that the browser developers know the correct way to determine whether a year is a leap year! (It's more complicated than a simple mod 4 == 0) Here is a quote from Wikipedia's page on leap years: " The Gregorian calendar, the current standard calendar in most of the world, adds a 29th day to February in all years evenly divisible by 4, except for centennial years (those ending in '00'), which receive the extra day only if they are evenly divisible by 400. Thus 1600, 2000 and 2400 are leap years but 1700, 1800, 1900 and 2100 are not. "

How does this function work? It is quite simple. When the Date() function is given a day number that is greater than the number of days in the given month of the given year, it wraps the date into the next month. The getDate() function returns the day of the month, starting from the beginning of the month that the date is in. So, day 32 of March is considered to be day 1 of April. Subtracting 1 from 32 gives the correct number of days in March!