Friday, December 7, 2012

EventLogProvider

<The following exception was thrown by the web event provider 'EventLogProvider' in the application '/applicationname' (in an application lifetime a maximum of one exception will be logged per provider instance):
System.Web.HttpException: The EventLogWebEventProvider provider failed to log an event with the error code 0x80070057.
at System.Web.Management.EventLogWebEventProvider.ProcessEvent(WebBaseEvent eventRaised)at System.Web.Management.WebBaseEvent.RaiseInternal(WebBaseEvent eventRaised, ArrayList firingRuleInfos, Int32 index0, Int32 index1)

What is EventLogProvider
EventLogProvider is one of the ASP.NET providers. .NET 2.0 comes with web event providers for logging web events in the windows event log (EventLogWebEventProvider).
Web event providers provide the interface between ASP.NET's health monitoring subsystem and data sources that log or further process the events ("Web events") fired by that subsystem.

Can we troubleshoot from this log?
Error code 0x80070057 means invalid parameter. When EventLogProvider tried to log an entry, it found that an invalid parameter was passed to the function call.
It is hard to debug as we don't know what parameters were passed.

How to enhance in the future.
We can custom Web Event Provider by deriving from System.Web.Management.WebEventProvider. By doing this we can log web events in media not supported by the built-in web event providers.

How to manually generate Event ID using EventCreate command

How to manually generate Event ID using EventCreate command
Link: http://winplat.net/post/2010/10/21/How-to-manually-generate-Event-ID-using-EventCreate-command.aspx
There are times when you need to generate event id of your choice. Probably you need your script to generate some event id on some event or just to test something you need an event. Windows lets you generate event id manually without having programming knowledge, by using EventCreate command line utility.
The EventCreate.exe lets you generate event id between the range of 0 – 1000. To generate event id above 1000, you may need LogEvent.exe.
This utility comes with windows, you simply need to open the command prompt and type in the command. Here is the syntax for the command:
EventCreate /S <Computer> /ID <Event ID> /L <Log Name> /SO <Source name> /T <Type> /D <Event log Description>

where /S is the computer name on which event should be generated. For local computer, omit this switch
/ID is the event id. You can specify a number from 0 to 1000 only.
/L is the event log you want to create event in. Valid parameters are: System and Application
/SO is the Source name for the Event.
/T is the Event Type. Valid parameters are: Success, Warning, Information and Error
/D is the Event log description. Ensure that you mention the message in quotes.
For example:
EC2
In above example, We created Event ID 50 with Source ‘Winplat.Net’ and type Error. The event log description says: “This is a test error”

If you want to generate an event with a different user account context then we have to use switches:
/U: Username under which the command should execute
/P: Password for the username provided. If this switch is omitted, you will be prompted for it.

Please Note: EventCreate.exe lets you generate event id ranging from 0-1000 only. To generate an event id above 1000, you need to use LogEvent.exe. Click here to jump to the article on LogEvent.exe.

Event Sources (Windows)
Link: http://msdn.microsoft.com/en-us/library/windows/desktop/aa363661(v=vs.85).aspx

Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry. The Security log is for system use only. Device drivers should add their names to the System log. Applications and services should add their names to the Application log or create a custom log.
The structure of the event sources is as follows:

HKEY_LOCAL_MACHINE
   SYSTEM
      CurrentControlSet
         Services
            EventLog
               Application
                  AppName
               Security
               System
                  DriverName
               CustomLog
                  AppName
You cannot use a source name that has already been used as a log name. In addition, source names cannot be hierarchical; that is, they cannot contain the backslash character ("\").
Each event source contains information (such as a message file) specific to the software that will be logging the events,, as shown in the following table.
Registry ValueDescription
CategoryCountNumber of event categories supported. This value is of type REG_DWORD.
CategoryMessageFilePath to the category message file. A category message file contains language-dependent strings that describe the categories. This value can be of type REG_SZ or REG_EXPAND_SZ.
EventMessageFilePath to one or more event message files; use a semicolon to delimit multiple files. An event message file contains language-dependent strings that describe the events. This value can be of type REG_SZ or REG_EXPAND_SZ.
ParameterMessageFilePath to the parameter message file. A parameter message file contains language-independent strings that are to be inserted into the event description strings. This value can be of type REG_SZ or REG_EXPAND_SZ.
TypesSupportedBitmask of supported types. This value is of type REG_DWORD. It can be one or more of the following values:
EVENTLOG_AUDIT_FAILURE (0x0010)
EVENTLOG_AUDIT_SUCCESS (0x0008)
EVENTLOG_ERROR_TYPE (0x0001)
EVENTLOG_INFORMATION_TYPE (0x0004)
EVENTLOG_WARNING_TYPE (0x0002)

When an application uses the RegisterEventSource or OpenEventLog function to get a handle to an event log, the event logging service searches for the specified event source in the registry. For example, the Application log might contain event sources for Microsoft SQL Server and Microsoft Excel. If an application uses RegisterEventSource or OpenEventLog with a source name of Application, SQL, or Excel, the event logging service returns a handle to the Application log.
An application can use the Application log without adding a new event source to the registry. If the application calls RegisterEventSource and passes a source name that cannot be found in the registry, the event-logging service uses the Application log by default. However, because there are no message files, the Event Viewer cannot map any event identifiers or event categories to a description string, and will display an error. For this reason, you should add a unique event source to the registry for your application and specify a message file.

Run: regedit
under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application
Add key  "appMail"
AddValue as following:
Default REG_SZ (value not set)
EventMessageFile REG_Expand_SZ C:\Windows\Microsoft.NET\Framework\v4.0.30319\EventLogMessages.dll
   No wyou can Run EventLog.WriteEntry to insert log by application
//if (!EventLog.SourceExists(sSource))
// EventLog.CreateEventSource(sSource, sLog);
EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Error,1);



Thursday, December 6, 2012

EventLog.WriteEntry Error – Requested registry access is not allowed

EventLog.WriteEntry Error – Requested registry access is not allowed
http://iamwanwan.wordpress.com/2011/12/13/eventlog-writeentry-error-requested-registry-access-is-not-allowed/

Write to EventLog using .Net C#
http://limherlina.blogspot.ca/2008/09/write-to-eventlog-using-net-c.html

VS : Writing to the event log FAILED .. Requested registry access is not allowed.
http://zeetalks.wordpress.com/2008/08/16/vs-writing-to-the-event-log-failed-requested-registry-access-is-not-allowed/


http://support.microsoft.com/kb/329291
http://support.microsoft.com/kb/842795

An unhandled exception of type 'System.Security.SecurityException' occurred in mscorlib.dll
Additional information: Requested registry access is not allowed.
 
This problem occurs because the user account that we used to create log does not have sufficient permissions.
 
We can solve the problem by 2 solutions below.

1. Add an application pool on IIS
    Change the default setting of this application pool.
    In Identity tag: change predefined value "Network Service"  to "Local system"
    Set  appMail service app to use this application pool.
 
2. Give the ASP.NET user permission to read from the event log registry entries.
Select Start - Run, then enter: regedt32
Navigate/expand to the following key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security
Right click on this entry and select Permissions
Add the ASPNET user
Give it Read permission


Wednesday, November 28, 2012

modalpopupextender updateprogress asp.net

http://csharpstepbystep.blogspot.ca/2011/10/aspnet-updateprogress-with.html
http://www.youtube.com/watch?v=_hRs21_dh_s

Javascript--enter key disable

How To: Disable Form Submit on Enter Key Press
http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx

The post Enter Key as the Default Button describes how to set the default behaviour for enter key press. However, sometimes, you need to disable form submission on Enter Key press. If you want to prevent it completely, you need to use OnKeyPress handler on <body> tag of your page.

<body OnKeyPress="return disableKeyPress(event)">

<script language="JavaScript">

function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox

return (key != 13);
}

</script>

If you want to disable form submission when enter key is pressed in an input field, you must use the function above on the OnKeyPress handler of the input field as follows:
<input type=”text” name=”txtInput” onKeyPress=”return disableEnterKey(event)”>

How to disable the Enter key on HTML form

http://webcheatsheet.com/javascript/disable_enter_key.php
Normally when you have a form with several text input fields, it is undesirable that the form gets submitted when the user hits ENTER in a field. Some people are pressing the enter key instead of the tab key to get to the next field. They often do that by accident or because they are accustomed to terminate field input that way. If a browser regards hitting ENTER in a text input field as a request to submit the form immediately, there is no sure way to prevent that.

Add the below script to the <head> section of your page. The following code disables the enter key so that visitors of your web page can only use the tab key to get to the next field.
<script type="text/javascript">

function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}

document.onkeypress = stopRKey;

</script>

Tuesday, October 23, 2012

asp.net anchor

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="Test" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="Test2.aspx#Link">

        錨點連結至Test2.aspx</asp:HyperLink>

    </div>

    </form>

</body>

</html>



<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Test2.aspx.vb" Inherits="Test2" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    第一行<br />
    1<br /><br /><br />
    2<br /><br /><br />
    3<br /><br /><br />
    4<br /><br /><br />
    5<br /><br /><br />
    6<br /><br /><br />
    7<br /><br /><br />
    8<br /><br /><br />
    9<br /><br /><br />
    10<br /><br /><br />
    <a id="Link"></a>
    錨點連結點11<br /><br /><br />
    12<br /><br /><br />
    13<br /><br /><br />
    14<br /><br /><br />
    15<br /><br /><br />
    </div>
    </form>
</body>
</html>

Thursday, October 18, 2012


 方法一:使用for循环
        int []pins = {9,3,7,2}
        int []copy = new int[pins.length];
        for(int i =0;i!=copy.length;i++)
        {
           copy[i] = pins[i];
         }
    方法二:使用数组对象中的CopyTo()方法
        int []pins = {9,3,7,2}
        int []copy2 = new int[pins.length];
        pins.CopyTo(copy2,0);
    方法三:使用Array类的一个静态方法Copy()
        int []pins = {9,3,7,2}
        int []copy3 = new int[pins.length];
        Array.Copy(pins,copy3,copy.Length);
    方法四:使用Array类中的一个实例方法Clone(),可以一次调用,最方便,但是Clone()方法返回的是一个对象,所以要强制转换成恰当的类类型。
        int []pins = {9,3,7,2}
        int []copy4 = (int [])pins.Clone();

Tuesday, September 25, 2012

Tuesday, September 18, 2012

  Public Sub mail(ByVal subject As String, ByVal message As String, ByRef errDesc As String)
        Try
            Dim smtp As New System.Net.Mail.SmtpClient()
            Dim mail As New System.Net.Mail.MailMessage()
            smtp.Credentials = New Net.NetworkCredential("", "")
            smtp.Port = 25
            smtp.Host = "ip"
            mail.From = New System.Net.Mail.MailAddress("abd@abd.com")
            mail.To.Add("lily@abd.com")
            mail.Subject = subject
            mail.Body = message
            smtp.Send(mail)
        Catch ex As Exception
            errDesc = ex.Message
        End Try
    End Sub

Thursday, August 23, 2012

html js

//javascript get value from get method and dispaly in html file
<script type="text/javascript">
  function getParameterByName(name) {
                name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
                var regexS = "[\\?&]" + name + "=([^&#]*)";
                var regex = new RegExp(regexS);
                var results = regex.exec(window.location.search);
                if (results == null)
                    return "";
                else return decodeURIComponent(results[1].replace(/\+/g, " "));
            }
document.write("<font color='yellow'>Total amount will be charge from you bank: $" + a+"</font>");
document.write("<input type='text' name='IDEBIT_AMOUNT' value='" + amount + "' />");
 </script>

//js get value from get method and set value to html controlfunction window.onload() {
        var amount = getParameterByName("amount");
        var orderID = getParameterByName("glvTransID");
        var merchdata = getParameterByName("data");
      
        document.getElementById("IDEBIT_AMOUNT").value = amount;
        document.getElementById("IDEBIT_INVOICE").value = orderID;
        document.getElementById("IDEBIT_MERCHDATA").value = merchdata;
}

Wednesday, August 22, 2012

pass value between pages

1.post  Server.Transfer same server
page1:
<asp:TextBox ID="id" runat="server" Text="456"  ></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
 protected void Button1_Click(object sender, EventArgs e)
 {        
            Server.Transfer("page2.aspx");
 }

 <input type='text' id='orderid' name='orderid' value='<% Response.Write(Page.Request.Form["id"]);%>' />  
<asp:ImageButton ID="ImageButton1" runat="server" PostBackUrl="~/LoadGLVisa.aspx"></asp:ImageButton>

2 aspx page by session
1st page set session
2nd page:
 <script type="text/javascript">
var x  = "<%=Session["id"].ToString()%> ";
 document.write(" <input type='text' id='orderid' name='orderid' value='"+x+"' />")*/ 
</script>

3.get data by get method  and display in html tag
<input type='hidden' id='orderid' name='orderid' value='<% Response.Write(Page.Request.QueryString["id"]);%>' />

4. hidden

page1:
  <asp:HiddenField ID="orderid" runat="server"  />
pageload: orderid.Value = "123456";
protected void Button1_Click(object sender, EventArgs e)
        {        
            Server.Transfer("test.aspx");
        }

page2:pageload
  HiddenField1.Value = Request.Form["orderid"].ToString();

 <asp:HiddenField ID="HiddenField1" runat="server" />
  <asp:ImageButton ID="ImageButton1" runat="server" PostBackUrl="~/LoadGLVisa.aspx" />

page3 load
 string orderid = Request.Form["HiddenField1"].ToString();

Friday, August 10, 2012

REG


Email
^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$

Credit card
 ^((4\d{3})|(5[1-5]\d{2})|(6011))-?\d{4}-?\d{4}-?\d{4}|3[4,7][\d\s-]{13}$

Friday, August 3, 2012

MOD 10

LUHN Algorithm in C# (Validate Credit Card)

 public static bool IsCreditCardValid(string cardNumber)
        {
            const string allowed = "0123456789";
            int i;
            StringBuilder cleanNumber = new StringBuilder();
            for (i = 0; i < cardNumber.Length; i++)
            {
                if (allowed.IndexOf(cardNumber.Substring(i, 1)) >= 0)
                    cleanNumber.Append(cardNumber.Substring(i, 1));
            }
            if (cleanNumber.Length < 13 || cleanNumber.Length > 16)
                return false;
            for (i = cleanNumber.Length + 1; i <= 16; i++)
                cleanNumber.Insert(0, "0");
            int multiplier, digit, sum, total = 0;
            string number = cleanNumber.ToString();
            for (i = 1; i <= 16; i++)
            {
                int n = i - 1;
                multiplier = 1 + (i % 2);
                digit = int.Parse(number.Substring(n, 1));
                sum = digit * multiplier;
                if (sum > 9)
                    sum -= 9;
                total += sum;
            }
            return (total % 10 == 0);
        }
http://www.notesbit.com/index.php/web-mysql/web-scripts/luhn-algorithm-in-c/

Thursday, August 2, 2012

Redirect page from http to https


1.
response.redirect(Request.ApplicationPath + "/Homepage.aspx");

2.
if(Request.ServerVariables["HTTPS"].ToLower() == "off")
{
strBaseURL = "http://";
}
else
{
strBaseURL = "https://";
}
strBaseURL = strBaseURL + Request.ServerVariables["SERVER_NAME"] + ":";
strBaseURL = strBaseURL + Request.ServerVariables["SERVER_PORT"];
strBaseURL = strBaseURL + Request.ServerVariables["URL"];

3.
1.) You could add a few lines of code to
your Global.asax file for the
Application_BeginRequest event handler. This handler would simply check the
current page request, via Request.Path.EndsWith("/PageName.aspx"), for
either of the two pages you need to be secure. Once it's determined if the
page requested needs to be secure, check Request.IsSecureConnection to see
if the request was already made via HTTPS. If not, redirect to
Request.Path.Replace("http://", "https://"). If the requested page is not
one of those two pages yet Request.IsSecureConnection returns True, then
redirect to Request.Path.Replace("https://", "http://") to undo the secure
connection.

2.) Another alternative is to create an HttpModule that you can install with
each project, or for the entire server via machine.config, that reads a
custom configuration section from your web.config file for the pages and
directories that need to be secured and any pages and directories that
should be ignored (i.e. requests that should remain in the protocal they
were requested). This class would read those pages into a searchable
collection and test for a match with the current requested page from the
BeginRequest event once again. A decision to redirect is made there.

4.
Switching Between HTTP and HTTPS Automatically: Version 2
http://www.codeproject.com/Articles/7206/Switching-Between-HTTP-and-HTTPS-Automatically-Ver

5.
if (!Request.IsLocal && !Request.IsSecureConnection)
{
string redirectUrl = Request.ApplicationPath + "/test.html?amount=" + amount;
//redirectUrl = Request.Url.ToString().Replace("http:", "https:");
redirectUrl = redirectUrl.ToString().Replace("http:", "https:");
Response.Redirect(redirectUrl);
}

6.
Global.asax
void Application_BeginRequest(object sender, EventArgs e)
{
int i = Request.Path.IndexOf("securepage.html");
//Request.Path="/index.aspx"
if (i != -1)  //is securepage.html,
{
   if (!Request.IsSecureConnection) //Request.IsSecureConnection=false  request is http  
{
         string path = string.Format("https{0}", Request.Url.AbsoluteUri.Substring(4));
         //Request.Url.AbsoluteUri="http://localhost:1234/securepage.html"
         //path="
https://localhost:1234/securepage.html"        
         Response.Redirect(path);
    }
}
else//any other page{}
}

7.
 void Application_BeginRequest(object sender, EventArgs e)
{
  if (Request.Path.EndsWith("/index.aspx"))
    {
       if (!Request.IsSecureConnection)// http
         {                   
            string securePath=Request.Url.AbsoluteUri.ToString().Replace("http://", "https://");
            //securePath=https://
            Response.Redirect(securePath);
          }
     }
     else
     {
              
      }              
}

8.
if (!Request.IsLocal && !Request.IsSecureConnection)           
{
  string s1 = Request.ApplicationPath + "index.asxp";
  // Request.ApplicationPath=”/”;
  // s1= “/index.aspx”
  string s2 = Request.Url.ToString().Replace("http:", "https:"); 
  // Request.Url=http://localhost:1234/index.aspx
  //    s2= https://localhost:1234/index.aspx  
  Response.Redirect(s1);
}

9.
string strBaseURL = "";
if (Request.ServerVariables["HTTPS"].ToLower() == "off")
{
   strBaseURL = "http://";
}
else
{
   strBaseURL = "https://";
}
strBaseURL = strBaseURL + Request.ServerVariables["SERVER_NAME"] + ":";
//https://localhost:
strBaseURL = strBaseURL + Request.ServerVariables["SERVER_PORT"];
//https://localhost:1234
strBaseURL = strBaseURL + Request.ServerVariables["URL"];
//https://localhost:1234/test.aspx
strBaseURL = strBaseURL.Replace("LoadGLVisa.aspx", "index.aspx");
//https://localhost:1234/index.aspx
Response.Redirect(strBaseURL);        
                  

Thursday, July 26, 2012

Response.Redirect throws an Thread was being aborted

original from:
http://briancaos.wordpress.com/2010/11/30/response-redirect-throws-an-thread-was-being-aborted/

Response.Redirect causes the browser to redirect to a different URL. It does so by sending a 302 – Object Moved to the browser, requesting it to do another roundtrip to the new page. Here is an example:
protected void Page_Load(object sender, EventArgs e)
{
  try
       {
           if (somethingIsTrue)
          Response.Redirect("http://", true);
       }
catch (Exception ex)
{
           // All exceptions are caught and written
           // to a log file
}
}
But here
 is something I didn’t know. When doing the Response.Redirect, .net will automatically throw an System.Threading.ThreadAbortException when the redirect is called. Apparently this is by design (although I’m nor sure I agree with the design).
The code above will write a log line for each time the Response.Redirect is called. This will flood my log file.
There are 4 solutions.
1) Set the EndResponse (the 2nd parameter) to false. The thread is aborted when the response is ended, so if you do not end the response, no abortion is done (this is untested, but according to several blogs valid).

2) Move the Response.Redirect outside the try/catch block.

3) Filter the exceptions. Do nothing if the ThreadAbortException occurs:

protected void Page_Load(object sender, EventArgs e)
{
 try
{
 if (somethingIsTrue)
Response.Redirect("http://www.pentia.dk/", true);
}
catch (ThreadAbortException ex1)
{
// do nothing
}
catch (Exception ex2)
{
// All remaining exceptions are caught and&nbsp;written
 // to a log file
}
}

4) Do not use Response.Redirect. Instead, modify the response headers (this is the rather stupid solution, but I have added it to show that you can redirect without using Response.Redirect):

Response.Clear();
Response.Status = "302 Object Moved";
Response.RedirectLocation = "http://www.pentia.dk/";
Response.End();

Thursday, July 19, 2012

break/continue/rturn

break 用法
break 语句用于终止最近的封闭循环或它所在的switch 语句。控制传递给终止语句后面的语句(如果有的话)。
说明
通常在 switch 语句和 while、for、for...in、或 do...while 循环中使用 break 语句。 最一般的是在 switch 语句中,但它可在任何语句中使用,无论是简单语句还是复合语句。
执行 break 语句会退出当前循环或语句,并开始执行紧接着的语句
break 示例
-----------------------------------------------------------------------------


在此例中,条件语句包含一个应该从 1 计数到 100 的计数器;
但 break 语句在计数达到 4 后终止循环。
// statements_break.cs
using System;
class BreakTest
{
static void Main()
{
for (int i = 1; i <= 100; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
}
}
输出
1
2
3
4
----------------------------------------
下面的示例演示 break 在switch语句中的用法。
// statements_break2.cs
// break and switch
using System;
class Switch
{
static void Main()
{
Console.Write("Enter your selection (1, 2, or 3): ");
string s = Console.ReadLine();
int n = Int32.Parse(s);

switch (n)
{
case 1:
Console.WriteLine("Current value is {0}", 1);
break;
case 2:
Console.WriteLine("Current value is {0}", 2);
break;
case 3:
Console.WriteLine("Current value is {0}", 3);
break;
default:
Console.WriteLine("Sorry, invalid selection.");
break;
}
}
}输入1示例输出Enter your selection (1, 2, or 3): 1Current value is 1如果输入了 4,则输出为: Enter your selection (1, 2, or 3): 4Sorry, invalid selection.


break语句:
break语句会使运行的程序立刻退出包含在最内层的循环或者退出一个switch语句。由于它是用来退出循环或者switch语句,所以只有当它出现在这些语句时,这种形式的break语句才是合法的。

如果一个循环的终止条件非常复杂,那么使用break语句来实现某些条件比用一个循环表达式来表达所有的条件容易得多。
for(var i=1;i<=10;i++)
{
if(i==6) break;
document.write(i);
}
//输出结果:12345

continue语句:
continue语句和break语句相似。所不同的是,它不是退出一个循环,而是开始循环的一次新迭代。
continue语句只能用在while语句、
do/while语句、for语句、或者for/in语句的循环体内,在其它地方使用都会引起错误!

for(var i=1;i<=10;i++)
{ if(i==6) continue;
document.write(i);
}
//输出结果:1234578910


return语句:
return语句就是用于指定函数返回的值。return语句只能出现在函数体内,出现在代码中的其他任何地方都会造成语法错误!
当执行return语句时,即使函数主体中还有其他语句,函数执行也会停止!

ref and out

ref是传递参数的地址,out是返回值,两者有一定的相同之处,不过也有不同点。

使用ref前必须对变量赋值,out不用。

out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。

区别可以参看下面的代码:

using System;
class TestApp
{
 static void outTest(out int x, out int y)
 {//离开这个函数前,必须对x和y赋值,否则会报错。
  //y = x;
  //上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行
  x = 1;
  y = 2;
 }
 static void refTest(ref int x, ref int y)
 {
  x = 1;
  y = x;
 }
 public static void Main()
 {
  //out test
  int a,b;
  //out使用前,变量可以不赋值
  outTest(out a, out b);
  Console.WriteLine("a={0};b={1}",a,b);
  int c=11,d=22;
  outTest(out c, out d);
  Console.WriteLine("c={0};d={1}",c,d);

  //ref test
  int m,n;
  //refTest(ref m, ref n);
  //上面这行会出错,ref使用前,变量必须赋值

  int o=11,p=22;
  refTest(ref o, ref p);
  Console.WriteLine("o={0};p={1}",o,p);
 }
}

Tuesday, May 8, 2012

DataRelations in ADO.NET


SELECT    c.CustomerID,    c.CompanyName,    c.ContactName,    o.OrderID,    o.OrderDate,    od.ProductID,    p.ProductName,    od.UnitPrice,   od.Quantity
FROM    Customers c    INNER JOIN Orders o ON c.CustomerID = o.CustomerID
    INNER JOIN [Order Details] od ON o.OrderID = od.OrderID
    INNER JOIN Products p ON od.ProductID = p.ProductID

string sCn = ". . . ";
SqlConnection oCn = new SqlConnection (sCn);
DataSet oDs = new DataSet();
//— Fill the customer DataTable
string sSqlCustomer = "SELECT CustomerID, CompanyName, ContactName FROM Customers";
SqlDataAdapter oDaCustomer = new SqlDataAdapter(sSqlCustomer, oCn);
oDaCustomer.Fill(oDs, "Customer");

//— Fill the order DataTable
string sSqlOrder = "SELECT CustomerID, OrderID, OrderDate FROM Orders";
SqlDataAdapter oDaOrder = new SqlDataAdapter(sSqlOrder, oCn);
oDaOrder.Fill(oDs, "Order");

//— Fill the order detail DataTable
string sSqlOrderDetail = "SELECT od.OrderID, od.ProductID,
                p.ProductName, " +
                " od.UnitPrice, od.Quantity FROM [Order Details] od " +
                " INNER JOIN Products p ON od.ProductID = p.ProductID";
SqlDataAdapter oDaOrderDetail = new SqlDataAdapter(sSqlOrderDetail, oCn);
oDaOrderDetail.Fill(oDs, "OrderDetail");

//— Create the DataRelation and relate the customers to their orders
DataRelation oDr_Customer2Order = new DataRelation("Customer2Order",
            oDs.Tables["Customer"].Columns["CustomerID"],
            oDs.Tables["Order"].Columns["CustomerID"]);
oDs.Relations.Add(oDr_Customer2Order);

//— Create the DataRelation and relate the orders to their order details
DataRelation oDr_Order2OrderDetail = new        
            DataRelation("Order2OrderDetail",
            oDs.Tables["Order"].Columns["OrderID"],
            oDs.Tables["OrderDetail"].Columns["OrderID"]);
oDs.Relations.Add(oDr_Order2OrderDetail);

dataGrid1.DataSource = oDs;

ForeignKeyConstraint oFKey;
oFKey = new ForeignKeyConstraint("CustomerForeignkey",
    oDs.Tables["Customer"].Columns["CustomerID"],  oDs.Tables["Order"].Columns["CustomerID"]);
oFKey.DeleteRule = Rule.Cascade;
oFKey.UpdateRule = Rule.Cascade;
oDs.Tables["Customer"].Constraints.Add(oFKey);
oDs.EnforceConstraints = true;

//— Retrieve the child rows for the first customer
DataRow[] oRows = oDs.Tables["Customer"].Rows[0].GetChildRows(oDr_Customer2Order);
string sMsg = "The orders for the first customer are: \n";
//— Loop through the child rows for the first customer
for (int i=0; i < oRows.Length; i++)
{
//— Grab the values for each child row of the first customer
    DataRow oRow = oRows[i];
    sMsg += "\t" + oRow["CustomerID"].ToString() +
            " " + oRow["OrderID"].ToString() +
            " " + oRow["OrderDate"].ToString() + "\n";
}
//— Display the values of the child rows
MessageBox.Show(sMsg);

DataRow oRow =  oDs.Tables["Order"].Rows[0].GetParentRow(oDr_Customer2Order);
MessageBox.Show(oRow["CompanyName"].ToString());

MessageBox.Show(oDs.GetXml());