Monday, December 22, 2008

my second windows form

Form1.Designer.cs

using System.Drawing;//
using System.Windows.Forms;//
using System;//
namespace MyPhoto
{
partial class Form1
{
///
/// Required designer variable.
///

private System.ComponentModel.IContainer components = null;

///
/// Clean up any resources being used.
///

/// true if managed resources should be disposed; otherwise, false.
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code

///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox1.Location = new System.Drawing.Point(24, 29);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(234, 200);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(284, 25);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.loadToolStripMenuItem,
this.toolStripSeparator1,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(39, 21);
this.fileToolStripMenuItem.Text = "&File";
//
// loadToolStripMenuItem
//
this.loadToolStripMenuItem.Name = "loadToolStripMenuItem";
this.loadToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.L)));
this.loadToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.loadToolStripMenuItem.Text = "&Load";
this.loadToolStripMenuItem.Click += new System.EventHandler(this.HandleLoadClick);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(149, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 264);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "Form1";
this.Text = "hello Form1";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();

}

#endregion

private void HandleLoadClick(object sender, System.EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Photo";
dlg.Filter = "jpg files(*.jpg)|*.jpg|All files(*.*)|*.*";

if (dlg.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox1.Image = new Bitmap(dlg.OpenFile());
}
catch (ArgumentException ex)
{
MessageBox.Show("Unable to upload the file: "+ex.Message);
}
}
dlg.Dispose();
}

private System.Windows.Forms.PictureBox pictureBox1;
private MenuStrip menuStrip1;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private ToolStripSeparator toolStripSeparator1;
private ToolStripMenuItem exitToolStripMenuItem;
}
}

my first windows form

Form1.Designer.cs

using System.Windows.Forms;
using System.Drawing;
namespace MyForm
{
partial class Form1
{
///
/// Required designer variable.
///

private System.ComponentModel.IContainer components = null;

///
/// Clean up any resources being used.
///

/// true if managed resources should be disposed; otherwise, false.
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code

///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(54, 28);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Load";
this.button1.UseVisualStyleBackColor = true;
this.button1.Left = 10;
this.button1.Top = 10;
this.button1.Click += new System.EventHandler(this.HandleLoadClick);
this.button1.Anchor = AnchorStyles.Top | AnchorStyles.Left;
//
// pictureBox1
//
this.pictureBox1.Location = new System.Drawing.Point(54, 85);
this.pictureBox1.Name = "pictureBox1";
//this.pictureBox1.Size = new System.Drawing.Size(179, 119);
this.pictureBox1.TabIndex = 1;
this.pictureBox1.TabStop = false;
this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.pictureBox1.Width = this.Width / 2;
this.pictureBox1.Height = this.Height / 2;
pictureBox1.Left = (this.Width - pictureBox1.Width) / 2;
pictureBox1.Top = (this.Height - pictureBox1.Height) / 2;
this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
this.pictureBox1.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;

//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(476, 327);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Hello Form";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);

}

#endregion

private void HandleLoadClick(object sender,System.EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Photo";
dlg.Filter = "jpg files(*.jpg)|*.jpg|All files(*.*)|*.*";

if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(dlg.OpenFile());
}
dlg.Dispose();
}

private System.Windows.Forms.Button button1;
private System.Windows.Forms.PictureBox pictureBox1;

}
}

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyForm
{
static class Program
{
///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

Wednesday, December 3, 2008

用javascript 返回上一级页面

<input id="Button1" type="button" value="button" onclick="javascript:history.go(-1);" />

用这个onclick="javascript:history.go(-1);"方法可以实现页面返回功能,而且父页面保持原状态(即跳转到子页面之前的状态)。

鼠标悬停在控件上时候出现气泡提示语

<asp:TextBox ID="TextBox1" runat="server" title="请输入用户名"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" title="请输入用户名" />

Tuesday, December 2, 2008

C#文件读写常用类介绍(转载)

C#文件读写常用类介绍
Source:http://www.sz-accp.com.cn/xxyd/ShowArticle.asp?ArticleID=625,
首先要熟悉.NET中处理文件和文件夹的操作。File类和Directory类是其中最主要的两个类。了解它们将对后面功能的实现提供很大的便利。
  本节先对和文件系统相关的两个.NET类进行简要介绍。
  System.IO.File类和System.IO.FileInfo类主要提供有关文件的各种操作,在使用时需要引用System.IO命名空间。下面通过程序实例来介绍其主要属性和方法。
  (1) 文件打开方法:File.Open ()
  该方法的声明如下:
public static FileStream Open(string path,FileMode mode)
  下面的代码打开存放在c:\tempuploads目录下名称为newFile.txt文件,并在该文件中写入hello。
private void OpenFile()
{
 FileStream.TextFile=File.Open(@"c:\tempuploads\newFile.txt",FileMode.Append);
 byte [] Info = {(byte)'h',(byte)'e',(byte)'l',(byte)'l',(byte)'o'};
 TextFile.Write(Info,0,Info.Length);
 TextFile.Close();
}
protected void myOpenFile(string msg)
{
StreamWriter sw = new StreamWriter(@"H:\SampleCode\ReadAndWriteFile\NewFile\SampleFile.txt");

sw.WriteLine(msg);
sw.Close();
}
  (2) 文件创建方法:File.Create()
  该方法的声明如下:
public static FileStream Create(string path;)
  下面的代码演示如何在c:\tempuploads下创建名为newFile.txt的文件。
  由于File.Create方法默认向所有用户授予对新文件的完全读/写访问权限,所以文件是用读/写访问权限打开的,必须关闭后才能由其他应用程序打开。为此,所以需要使用FileStream类的Close方法将所创建的文件关闭。
private void MakeFile()
{  
FileStream NewText=File.Create(@"c:\tempuploads\newFile.txt");
 NewText.Close();
} 
(3) 文件删除方法:File.Delete()
  该方法声明如下:
public static void Delete(string path);
  下面的代码演示如何删除c:\tempuploads目录下的newFile.txt文件。
private void DeleteFile()
{
 File.Delete(@"c:\tempuploads\newFile.txt");
}
  (4) 文件复制方法:File.Copy

  该方法声明如下:

public static void Copy(string sourceFileName,string destFileName,bool overwrite);
  下面的代码将c:\tempuploads\newFile.txt复制到c:\tempuploads\BackUp.txt。
  由于Cope方法的OverWrite参数设为true,所以如果BackUp.txt文件已存在的话,将会被复制过去的文件所覆盖。
private void CopyFile()
{
 File.Copy(@"c:\tempuploads\newFile.txt",@"c:\tempuploads\BackUp.txt",true);
}
  (5) 文件移动方法:File.Move
  该方法声明如下:
public static void Move(string sourceFileName,string destFileName);
  下面的代码可以将c:\tempuploads下的BackUp.txt文件移动到c盘根目录下。
  注意:
  只能在同一个逻辑盘下进行文件转移。如果试图将c盘下的文件转移到d盘,将发生错误。
private void MoveFile()
{
 File.Move(@"c:\tempuploads\BackUp.txt",@"c:\BackUp.txt");
}
 (6) 设置文件属性方法:File.SetAttributes
  该方法声明如下:
public static void SetAttributes(string path,FileAttributes fileAttributes);
  下面的代码可以设置文件c:\tempuploads\newFile.txt的属性为只读、隐藏。
private void SetFile()
{
 File.SetAttributes(@"c:\tempuploads\newFile.txt",
 FileAttributes.ReadOnly|FileAttributes.Hidden);
}
  文件除了常用的只读和隐藏属性外,还有Archive(文件存档状态),System(系统文件),Temporary(临时文件)等。关于文件属性的详细情况请参看MSDN中FileAttributes的描述。
  (7) 判断文件是否存在的方法:File.Exist
  该方法声明如下:
public static bool Exists(string path);
  下面的代码判断是否存在c:\tempuploads\newFile.txt文件。若存在,先复制该文件,然后其删除,最后将复制的文件移动;若不存在,则先创建该文件,然后打开该文件并进行写入操作,最后将文件属性设为只读、隐藏。
if(File.Exists(@"c:\tempuploads\newFile.txt")) //判断文件是否存在
{
 CopyFile(); //复制文件
 DeleteFile(); //删除文件
 MoveFile(); //移动文件
}
else
{
 MakeFile(); //生成文件
 OpenFile(); //打开文件
 SetFile(); //设置文件属性
}
  此外,File类对于Text文本提供了更多的支持。
  · AppendText:将文本追加到现有文件
  · CreateText:为写入文本创建或打开新文件
  · OpenText:打开现有文本文件以进行读取
  但上述方法主要对UTF-8的编码文本进行操作,从而显得不够灵活。在这里推荐读者使用下面的代码对txt文件进行操作。
  · 对txt文件进行“读”操作,示例代码如下:
StreamReader TxtReader = new StreamReader(@"c:\tempuploads\newFile.txt",System.Text.Encoding.Default);
string FileContent;
FileContent = TxtReader.ReadEnd();
TxtReader.Close();
  · 对txt文件进行“写”操作,示例代码如下:
StreamWriter = new StreamWrite(@"c:\tempuploads\newFile.txt",System.Text.Encoding.Default);
string FileContent;
TxtWriter.Write(FileContent);
TxtWriter.Close();
  System.IO.Directory类和System.DirectoryInfo类
  主要提供关于目录的各种操作,使用时需要引用System.IO命名空间。下面通过程序实例来介绍其主要属性和方法。
  (1) 目录创建方法:Directory.CreateDirectory
  该方法声明如下:
public static DirectoryInfo CreateDirectory(string path);
  下面的代码演示在c:\tempuploads文件夹下创建名为NewDirectory的目录。
private void MakeDirectory()
{
 Directory.CreateDirectory(@"c:\tempuploads\NewDirectoty");
}
  (2) 目录属性设置方法:DirectoryInfo.Atttributes
  下面的代码设置c:\tempuploads\NewDirectory目录为只读、隐藏。与文件属性相同,目录属性也是使用FileAttributes来进行设置的。
private void SetDirectory()
{
 DirectoryInfo NewDirInfo = new DirectoryInfo(@"c:\tempuploads\NewDirectoty");
 NewDirInfo.Atttributes = FileAttributes.ReadOnly|FileAttributes.Hidden;
}
  (3) 目录删除方法:Directory.Delete
  该方法声明如下:
public static void Delete(string path,bool recursive);
  下面的代码可以将c:\tempuploads\BackUp目录删除。Delete方法的第二个参数为bool类型,它可以决定是否删除非空目录。如果该参数值为true,将删除整个目录,即使该目录下有文件或子目录;若为false,则仅当目录为空时才可删除。
private void DeleteDirectory()
{
 Directory.Delete(@"c:\tempuploads\BackUp",true);
}
  (4) 目录移动方法:Directory.Move
  该方法声明如下:
public static void Move(string sourceDirName,string destDirName);
  下面的代码将目录c:\tempuploads\NewDirectory移动到c:\tempuploads\BackUp。
private void MoveDirectory()
{
 File.Move(@"c:\tempuploads\NewDirectory",@"c:\tempuploads\BackUp");
}
  (5) 获取当前目录下的所有子目录方法:Directory.GetDirectories
  该方法声明如下:
public static string[] GetDirectories(string path;);
  下面的代码读出c:\tempuploads\目录下的所有子目录,并将其存储到字符串数组中。
private void GetDirectory()
{
 string [] Directorys;
 Directorys = Directory. GetDirectories (@"c:\tempuploads");
}
  (6) 获取当前目录下的所有文件方法:Directory.GetFiles
  该方法声明如下:
public static string[] GetFiles(string path;);
  下面的代码读出c:\tempuploads\目录下的所有文件,并将其存储到字符串数组中。
private void GetFile()
{
 string [] Files;
 Files = Directory. GetFiles (@"c:\tempuploads",);
}
  (7) 判断目录是否存在方法:Directory.Exist
  该方法声明如下:
public static bool Exists(
 string path;
);
  下面的代码判断是否存在c:\tempuploads\NewDirectory目录。若存在,先获取该目录下的子目录和文件,然后其移动,最后将移动后的目录删除。若不存在,则先创建该目录,然后将目录属性设为只读、隐藏
if(File.Exists(@"c:\tempuploads\NewDirectory")) //判断目录是否存在
{
 GetDirectory(); //获取子目录
 GetFile(); //获取文件
 MoveDirectory(); //移动目录
 DeleteDirectory(); //删除目录
}
else
{
 MakeDirectory(); //生成目录
 SetDirectory(); //设置目录属性
}
  注意:
  路径有3种方式,当前目录下的相对路径、当前工作盘的相对路径、绝对路径。以C:\Tmp\Book为例(假定当前工作目录为C:\Tmp)。“Book”,“\Tmp\Book”,“C:\Tmp\Book”都表示C:\Tmp\Book。
  另外,在C#中 “\”是特殊字符,要表示它的话需要使用“\\”。由于这种写法不方便,C#语言提供了@对其简化。只要在字符串前加上@即可直接使用“\”。所以上面的路径在C#中应该表示为“Book”,@“\Tmp\Book”,@“C:\Tmp\Book”。 

Create Navigation Application with WPF

Monday, December 1, 2008

关于GridView数据行的鼠标悬停高亮的问题

其实这个问题很简单,只要两行代码就可以解决。

private void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#66CCFF'");
e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
}
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#6699ff';");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor;");
}
}

using Ajax to work with GridView




http://www.asp.net/learn/3.5-videos/video-362.aspx

Visual Studio 2008 - New Features

Introduction
Visual Studio 2008 code name "Orcas" Beta 2 has just hit the road and, since it is Beta 2, this means Visual Studio 2008 is feature complete and is ready for RTM. Below, we would find a brief introduction of some of the new features introduced with VS 2008 and .NET 3.5 Beta 2.

A quick list of some of the new features are:

Multi-Targeting support
Web Designer and CSS support
ASP.NET AJAX and JavaScript support
Project Designer
Data
LINQ – Language Integrated Query



The features listed and explained in this paper are not complete and this document intends to give you a forehand to start off with VS 2008.

1. Multi-Targeting Support
Earlier, each Visual Studio release only supported a specific version of the .NET Framework. For example, VS 2003 only works with .NET 1.1, and VS 2005 only works with .NET 2.0.

One of the major changes with the VS 2008 release is to support what Microsoft calls "Multi-Targeting". This means that Visual Studio will now support targeting multiple versions of the .NET Framework, and developers will be able to take advantage of the new features that Visual Studio provides without having to migrate their existing projects and deployed applications to use a new version of the .NET Framework.

Now when we open an existing project or create a new one with VS 2008, we can pick which version of the .NET Framework to work with. The IDE will update its compilers and feature-set to match the chosen .NET Framework.

Features, controls, projects, item-templates, and references that do not work with the selected version of the Framework will be made unavailable or will be hidden.

Unfortunately, support has not been included to work with Framework versions 1.1 and earlier. The present release supports 2.0/3.0 and 3.5 .NET Frameworks.

Microsoft plans to continue multi-targeting support in all future releases of Visual Studio.

Creating a New Project with Visual Studio 2008 that Targets .NET 2.0 Framework Library
The screenshots below depict the creation of a new web application targeting .NET 2.0 Framework. Choose File->New Project. As we see in the snapshot below in the top-right of the new project dialog, there is now a dropdown that allows us to choose which versions of the .NET Framework we want to target when we create the new project. The templates available are filtered depending on the version of the Framework chosen from the dropdown:



Can I Upgrade an Existing Project to .NET 3.5?
When we open a solution created using an older version of Visual Studio and Framework, VS 2008 would ask if migration is required. If we opt to migrate, then a migration wizard would start. If we wish to upgrade our project to target a newer version of the Framework at a later point of time, we can pull up the project properties page and choose the Target Framework. The required assemblies are automatically referenced. The snapshot below shows the properties page with the option Target Framework marked.


2. Web Designer, Editing and CSS Support
One feature that web developers will discover with VS 2008 is its drastically improved HTML designer, and the extensive CSS support made available.

The snapshots below depict some of the new web designer features in-built into VS 2008.

Split View Editing
In addition to the existing views, Design view and Code view, VS 2008 brings along the Split view which allows us to view both the HTML source and the Design View at the same-time, and easily make changes in any of the views. As shown in the image below, as we select a tag in code view, the corresponding elements/controls are selected in design view.


CSS Style Manager
VS 2008 introduces a new tool inside the IDE called "Manage Styles". This shows all of the CSS style sheets for the page.

It can be used when we are in any of the views - design, code and split views. Manage Styles tool can be activated by choosing Format -> CSS Styles -> Manage Styles from the menu. A snapshot of the same would look like the following:


Create a new style using the new style dialog window as show in the snapshot below.


Now, the style manager would show .labelcaption style as well in the CSS styles list. However, if we observe that the body element has a circle around it but the .labelcaption does not have one, this is because the style is not in use yet.


We will not select all the labels below and apply our new style .labelcaption.


We can choose to modify the existing style through GUI using "Modify style..." menu option in the dropdown menu as shown above or choose to hand edit the code by choosing the option "Go To Code".

CSS Source View Intellisense
The designer is equipped with the ability to select an element or control in design-view, and graphically select a rule from the CSS list to apply to it.

We will also find when in source mode that we now have intellisense support for specifying CSS class rules. The CSS Intellisense is supported in both regular ASP.NET pages as well as when working with pages based on master pages.


Code Editing Enhancements
Below is a non-exhaustive list of a few new code editing improvements. There are many more about which I don't know yet.

Transparent Intellisense Mode
While using VS 2005/2003 we often find ourselves escaping out of intellisense in order to better see the code around, and then go back and complete what we were doing.

VS 2008 provides a new feature which allows us to quickly make the intellisense drop-down list semi-transparent. Just hold down the "Ctrl" key while the intellisense drop-down is visible and we will be able to switch it into a transparent mode that enables us to look at the code beneath without having to escape out of Intellisense. The screenshot below depicts the same.


Organize C# Using Statements
One of the small, but a nice new feature in VS 2008 is support for better organizing using statements in C#. We can now select a list of using statements, right-click, and then select the "Organize Usings" sub-menu. When we use this command the IDE will analyze what types are used in the code file, and will automatically remove those namespaces that are declared but not required. A small and handy feature for code refactoring.


3. ASP.NET AJAX and JavaScript Support
JavaScript Intellisense
One new feature that developers will find with VS 2008 is its built-in support for JavaScript Intellisense. This makes using JavaScript and building AJAX applications significantly easier. A double click on HTML control in design mode would automatically create a click event to the button and would create the basic skeleton of the JavaScript function. As we see in the depicted image below, JavaScript Intellisense is inbuilt now. Other JavaScript Intellisense features include Intellisense for external JavaScript libraries and adding Intellisense hints to JavaScript functions.


JavaScript Debugging
One new JavaScript feature in VS 2008 is the much-improved support for JavaScript debugging. This makes debugging AJAX applications significantly easier. JavaScript debugging was made available in VS 2005 itself. However, we had to run the web application first to set the breakpoint or use the "debugger" JavaScript statement.

VS 2008 makes this much better by adding new support that allows us to set client-side JavaScript breakpoints directly within your server-side .aspx and .master source files.

We can now set both client-side JavaScript breakpoints and VB/C# server-side breakpoints at the same time on the same page and use a single debugger to step through both the server-side and client-side code in a single debug session. This feature is extremely useful for AJAX applications. The breakpoints are fully supported in external JavaScript libraries as well.

4. Few Other Features and Enhancements
Below is a list of few other enhancements and new features included in Microsoft Visual Studio 2008.

Project Designer
Windows Presentation Foundation (WPF) applications have been added to Visual Studio 2008. There are four WPF project types:

WinFX Windows Application
WinFX Web Browser Application
WinFX Custom Control Library
WinFX Service Library
When a WPF project is loaded in the IDE, the user interface of the Project Designer pages lets us specify properties specific to WPF applications.

Data
Microsoft Visual Studio 2008 Beta 2 includes the following new features to incorporate data into applications:

The Object Relational Designer (O/R Designer) assists developers in creating and editing the objects (LINQ to SQL entities) that map between an application and a remote database
Hierarchical update capabilities in Dataset Designer, providing generated code that includes the save logic required to maintain referential integrity between related tables
Local database caching incorporates an SQL Server Compact 3.5 database into an application and configures it to periodically synchronize the data with a remote database on a server. Local database caching enables applications to reduce the number of round trips between the application and a database server
LINQ – Language Integrated Query
LINQ is a new feature in VS 2008 that broadens great querying capabilities into the language syntax. LINQ introduces patterns for querying and updating data. A set of new assemblies are provided that enable the use of LINQ with collections, SQL databases, and XML documents.

Visual Studio 2008 Debugger
The Visual Studio 2008 debugger has been enhanced with the following features:

Remote debugging support on Windows Vista
Improved support for debugging multithreaded applications
Debugging support for LINQ programming
Debugging support for Windows Communications Foundation
Support for script debugging, including client-side script files generated from server-side script now appear in Solution Explorer


Reporting
Visual Studio 2008 provides several new reporting features and improvements such as:

New Report Projects: Visual Studio 2008 includes two new project templates for creating reporting applications. When we create a new Reports Application project, Visual Studio provides a report (.rdlc) and a form with a ReportViewer control bound to the report.
Report Wizard: Visual Studio 2008 introduces a Report Wizard, which guides us through the steps to create a basic report. After we complete the wizard, we can enhance the report by using Report Designer.
Expression Editor Enhancement: The Expression Editor now provides expressions that we can use directly or customize as required.
PDF Compression: The ReportViewer controls can now compress reports that are rendered or exported to the PDF format.

Thursday, November 27, 2008

怎样把COOKIE放到公共类里再调用

一个关于怎样把COOKIE放到公共类里再调用的问题

Default.aspx code

<body>
<form id="form1" runat="server">
<div>
<center>
<table>
<tr>
<td>UserName : </td>
<td>
<asp:TextBox ID="txtUser" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan=2>
<asp:Button ID="btnSubmit" runat="server" Text="Submit to Target"
onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</center>
</div>
</form>
</body>

Default.aspx.cs code

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

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
HttpCookie objCookUser = new HttpCookie("UserName",txtUser.Text.Trim().ToString());
HttpCookie objCookPwd = new HttpCookie("Password",txtPassword.Text.ToString().Trim());
Response.Cookies.Add(objCookUser);
Response.Cookies.Add(objCookPwd);
Server.Transfer("TargetPage.aspx");
}
}

TargetPage.aspx.cs code

public partial class TargetPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (System.Web.HttpContext.Current.Request.Cookies["UserName"] != null && System.Web.HttpContext.Current.Request.Cookies["Password"] != null)
{
Response.Write(System.Web.HttpContext.Current.Request.Cookies["UserName"].Value.ToString() + "<br/>" + System.Web.HttpContext.Current.Request.Cookies["Password"].Value.ToString());
}
}
}
}

Monday, November 24, 2008

Session State Sample

this is a session state practise:

Default.aspx Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Session State</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<h1>Session State</h1>
<h3>Select a book category</h3>

<asp:RadioButtonList ID="rdl" runat="server" CellPadding="20" RepeatColumns="3" RepeatDirection="Horizontal" OnSelectedIndexChanged="rdl_SelectedIndexChanged">
<asp:ListItem Value="n">.NET</asp:ListItem>
<asp:ListItem Value="d">DataBase</asp:ListItem>
<asp:ListItem Value="h">HardWare</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="btn" runat="server" Text="Submit" onclick="btn_Click" />
<br /><br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
<br /><br />
<asp:DropDownList ID="ddl" runat="server" Visible="false"></asp:DropDownList>
</center>
</div>
</form>
</body>
</html>

Default.aspx.cs Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Text;//necessary for StringBuilder

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

}
protected void rdl_SelectedIndexChanged(object sender, EventArgs e)
{
if (rdl.SelectedIndex != -1)
{
string[] Books = new string[3];
Session["cattext"] = rdl.SelectedItem.Text;
Session["catcode"] = rdl.SelectedItem.Value;

switch (rdl.SelectedItem.Value)
{
case "n":
Books[0] = "Programming C#";
Books[1] = "Programming ASP.NET";
Books[2] = "Programming Essentials";
break;
case "d":
Books[0] = "Oracle & Open Source";
Books[1] = "SQL in a NutShell";
Books[2] = "Transact-SQL Programming";
break;
case "h":
Books[0] = "PC Hardware in a Nutshell";
Books[1] = "Dictionary of PC Hardware and Data Communications Terms";
Books[2] = "Linux Device Drivers";
break;
}

Session["books"] = Books;
}
}
protected void btn_Click(object sender, EventArgs e)
{
if (rdl.SelectedIndex == -1)
{
lblMessage.Text = "You must select a book category.";
}
else
{
StringBuilder sb = new StringBuilder();
sb.Append("You have selected the category ");
sb.Append((string)Session["cattext"]);
sb.Append(" with code \"");
sb.Append((string)Session["catcode"]);
sb.Append("\".");
lblMessage.Text = sb.ToString();

ddl.Visible = true;
string[] CatBooks = (string[]) Session["books"];

//populate the DropDownList
ddl.Items.Clear();
for (int i = 0; i < CatBooks.GetLength(0); i++)
{
ddl.Items.Add(new ListItem(CatBooks[i]));
}
}
}
}

Sunday, November 23, 2008

Cross page is post back with different method

this is a page redirect sample (Server.Transfer, Response.Redirect, Cross-Page):

Default.aspx Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Cross-Page Posting</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<h1>Cross-Page Posting</h1>
Select your favorite activity: 
<asp:DropDownList ID="ddlFavoriteActivity" runat="server" AutoPostBack="true">
<asp:ListItem Text="Eating" />
<asp:ListItem Text="Sleeping" />
<asp:ListItem Text="Programming" />
<asp:ListItem Text="Watching TV" />
<asp:ListItem Text="Sex" />
<asp:ListItem Text="Skiing" />
<asp:ListItem Text="Bicycling" />
</asp:DropDownList>
<br /><br /><br />
<asp:Button ID="btnServerTransfer" runat="server" Text="Server.Transfer"
onclick="btnServerTransfer_Click" /> 
<asp:Button ID="btnRedirect" runat="server" Text="Response.Redirect"
onclick="btnRedirect_Click" /> 
<asp:Button ID="btnCrossPage" runat="server" Text="Cross-Page Post" PostBackUrl="~/TargetPage.aspx" />
<br /><br />
IsPostBack:
<asp:Label ID="lblIsPostBack" runat="server" Text="not defined"></asp:Label>
<br />
IsCrossPagePoatBack:
<asp:Label ID="lblIsCrossPagePostBack" runat="server" Text="not defined"></asp:Label>
<br />
PreviousPage:
<asp:Label ID="lblPreviousPage" runat="server" Text="not defined"></asp:Label>
</center>
</div>
</form>
</body>
</html>

Default.aspx.cs Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Threading;//necessary for ThreadAbortException

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblIsPostBack.Text = IsPostBack.ToString();
lblIsCrossPagePostBack.Text = IsCrossPagePostBack.ToString();
if (Page.PreviousPage != null)
{
lblPreviousPage.Text = Page.PreviousPage.Title;
}
}
protected void btnServerTransfer_Click(object sender, EventArgs e)
{
Server.Transfer("TargetPage.aspx");
}
protected void btnRedirect_Click(object sender, EventArgs e)
{
Response.Redirect("TargetPage.aspx");
}
}

TargetPage.aspx Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Target page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<h1>Target Page</h1>
<br />
Your favorite activity is :
<asp:Label ID="lblAcyivity" runat="server" Text="unknow"></asp:Label>
<br /><br />
IsPostBack:
<asp:Label ID="lblIsPostBack" runat="server" Text="not defined"></asp:Label>
<br />
IsCrossPagePoatBack:
<asp:Label ID="lblIsCrossPagePostBack" runat="server" Text="not defined"></asp:Label>
<br />
PreviousPage:
<asp:Label ID="lblPreviousPage" runat="server" Text="not defined"></asp:Label>
<br />
Previous Page IsPostBack :
<asp:Label ID="lblPreviousPageIsPostBack" runat="server" Text="not defined"></asp:Label>
<br />
Previous Page IsCrossPagePostBack :
<asp:Label ID="lblPreviousPageCrossPagePostBack" runat="server" Text="not defined"></asp:Label>
</center>
</div>
</form>
</body>
</html>

TargetPage.aspx.cs Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class TargetPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.PreviousPage != null)
{
DropDownList ddl = (DropDownList)Page.PreviousPage.FindControl("ddlFavoriteActivity");
if (ddl != null)
{
lblAcyivity.Text = ddl.SelectedItem.ToString() + "(late-bound)";
}
}
lblIsPostBack.Text = IsPostBack.ToString();
lblIsCrossPagePostBack.Text = IsCrossPagePostBack.ToString();
if (Page.PreviousPage != null)
{
lblPreviousPage.Text = Page.PreviousPage.Title;
lblPreviousPageIsPostBack.Text = Page.PreviousPage.IsPostBack.ToString();
lblPreviousPageCrossPagePostBack.Text = Page.PreviousPage.IsCrossPagePostBack.ToString();
}
}
}

How to Use MultiView and View

sometime we need use multiview to show some many content, this is a demo for it. Let's go!

client code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>This is a practice for MultiView and View</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<h1>MultiView and View</h1><br />
<asp:RadioButtonList ID="rdlView" runat="server" AutoPostBack="true"
RepeatDirection="Horizontal"
onselectedindexchanged="rdlView_SelectedIndexChanged">
<asp:ListItem Value="-1">Nothing</asp:ListItem>
<asp:ListItem Selected=True Value="0">First View</asp:ListItem>
<asp:ListItem Value="1">Second View</asp:ListItem>
<asp:ListItem Value="2">Third View</asp:ListItem>
<asp:ListItem Value="3">Last View</asp:ListItem>
</asp:RadioButtonList><br />
Current Index:
<asp:Label ID="lblCurrentIndex" runat="server"></asp:Label>
<br />
<asp:MultiView ID="MultiView1" runat="server"
onactiveviewchanged="MultiView1_ActiveViewChanged" ActiveViewIndex=0>
<asp:View ID="vwFirst" runat="server" OnActivate="ActivateView"
ondeactivate="DeactivateView">
<h2>First View</h2>
<asp:TextBox ID="txtFirstView" runat="server" />
<asp:Button ID="btnNext1" runat="server" CommandName="NextView" Text="Go to Next" />
<asp:Button ID = "btnLast" runat="server" CommandName="SwitchViewByID" CommandArgument="vwLast" Text = "Go to Last" />
</asp:View>
<asp:View ID="vwSecond" runat="server" OnActivate="ActivateView" OnDeactivate="DeactivateView">
<h2>Second View</h2>
<asp:TextBox ID="txtSecondView" runat="server"></asp:TextBox>
<asp:Button ID="btnNext2" runat="server" CommandName="NextView" Text="Go to Next" />
<asp:Button ID="btnPrevious2" runat="server" CommandName="PrevView" Text="Go to Previous" />
</asp:View>
<asp:View ID="vwThird" runat="server" OnActivate="ActivateView" OnDeactivate="DeactivateView">
<h2>Third View</h2>
<br />
<asp:Button ID="btnNext3" runat="server" CommandName="NextView" Text="Go to Next" />
<asp:Button ID="btnPrev3" runat="server" CommandName="PrevView" Text="Go to Previous" />
</asp:View>
<asp:View ID="vwLast" runat="server" OnActivate="ActivateView" OnDeactivate="DeactivateView">
<h2>Last View</h2>
<br />
<asp:Button ID="btnPrev4" runat="server" CommandName="PrevView" Text="Go to Previous" />
<asp:Button ID="btnFirst" runat="server" CommandName="SwitchViewByIndex" CommandArgument="0" Text="Go to First" />
</asp:View>
</asp:MultiView>
<br /><br />
First TextBox:
<asp:Label ID="lblFirstTextBox" runat="server"></asp:Label>
<br />
Second TextBox:
<asp:Label ID="lblSecondTextBox" runat="server"></asp:Label>
<br /><br />
<strong>
<span style="text-decoration:underline">
View Activation History:
</span>
</strong>
<br />
<asp:Label ID="lblViewActivation" runat="server"></asp:Label>
</center>
</div>
</form>
</body>
</html>

code behind:

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

}
protected void Page_PreRender(object sender, EventArgs e)
{
lblCurrentIndex.Text = MultiView1.ActiveViewIndex.ToString();
}
protected void rdlView_SelectedIndexChanged(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = Convert.ToInt32(rdlView.SelectedValue);
}
protected void ActivateView(object sender, EventArgs e)
{
string str = lblViewActivation.Text;
View v = (View)sender;
str += "View " + v.ID + " activated
";
lblViewActivation.Text = str;
}
protected void DeactivateView(object sender, EventArgs e)
{
string str = lblViewActivation.Text;
View v = (View)sender;
str += "View " + v.ID + " deactivated
";
lblViewActivation.Text = str;
}
protected void MultiView1_ActiveViewChanged(object sender, EventArgs e)
{
lblFirstTextBox.Text = txtFirstView.Text;
lblSecondTextBox.Text = txtSecondView.Text;
rdlView.SelectedIndex = MultiView1.ActiveViewIndex + 1;
}
}

comments:


1. in order to save you work, you can create a event group--ActivateView,DeactivateView, these group implement the same code for you.

2. please don't write the lblCurrentIndex.Text in the Page_Load() statement, because the page will be loaded before the label updated.
Just put the lblCurrentIndex.Text code in the Page_PreRender, this is a page event handler.

such as:


protected void Page_PreRender(object sender, EventArgs e)
{
lblCurrentIndex.Text = MultiView1.ActiveViewIndex.ToString();
}

Thursday, November 20, 2008

vs2008在编译时显示“无法显示该页面”

今天刚刚安装了vs2008和sql server2008,而且是在vista home 版本下边,运行了一个程序想体验一把vs2008,sql2008和vista的结合如何,结果按下F5后发现有错误,显示“该网页无法显示”,直接就晕了,vista home版本下是没有iis的,但是自从vs2005开始,编译运行时应该不再需要iis了(当然是在单机调试),我开始怀疑是不是安全权限设置有问题,因为vista的一个突出特点就是加入了许多的权限设置,于是大半夜的到网上搜啊,折腾了半天,才找到解决方案,不过这个方案应该不仅仅是适用于vista,其他的操作系统也有可能会遇见这样的问题,好了,看看我是怎么解决的吧。

开始-->运行-->输入c:\windows\system32\drivers\etc\hosts
这是会出现一个选框,你选择“记事本”,于是会有一个记事本文档,最下面有这样两行字:

127.0.0.1 localhost
::1 localhost

你只要将::1后面的localhost删除并保存即可以,修改后:

127.0.0.1 localhost
::1

保存后,再去运行vs2008里面的项目就可以了。简单吧?!!

其实问题的答案有时候真的很简单,不过要你不懈努力的去寻找才可以,这也许就是人们常说的会者不难难者不会。哈啊

Thursday, November 13, 2008

Tuesday, November 11, 2008

How to Create a dynamic web service

this is a sample about how to create webservice dynamicly. But at first, you must create a webservice on your local machine,
such as:http://localhost:2704/TestWebService/Service.asmx
OK, let's go !


code for default.aspx


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Dynamic Web Service Sample</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>WebService URL</td>
<td><asp:TextBox ID="wurl" runat="server">http://localhost:2704/TestWebService/Service.asmx</asp:TextBox></td>
</tr>
<tr>
<td>WebService Name</td>
<td><asp:TextBox ID="wname" runat="server">Service</asp:TextBox></td>
</tr>
<tr>
<td>Method Name</td>
<td><asp:TextBox ID="wmname" runat="server">RevSMS</asp:TextBox></td>
</tr>
<tr>
<td>Method Param0</td>
<td><asp:TextBox ID="wmparam0" runat="server">SYS06*</asp:TextBox></td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /></td>
</tr>
<tr>
<td colspan="4"><asp:TextBox ID="result" runat="server" TextMode="MultiLine" Width="100%" Height="100px"></asp:TextBox></td>
</tr>
</table>

</form>
</body>
</html>

code for default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
DynamicWebService we = new DynamicWebService("http://localhost:2704/TestWebService/Service.asmx", "Service");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
we = new DynamicWebService("http://localhost:2704/TestWebService/Service.asmx", "Service");
result.Text = we.InvokeMethod("HelloWorld", null).ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(wurl.Text)
&& !string.IsNullOrEmpty(wname.Text)
&& !string.IsNullOrEmpty(wmname.Text))
{
we = new DynamicWebService(wurl.Text, wname.Text);
result.Text = we.InvokeMethod(wmname.Text, string.IsNullOrEmpty(wmparam0.Text) ? null : new object[] { wmparam0.Text }).ToString();
}
}
}


code for DynamicWebService.cs

using System.Net;//for webclient
using System.Reflection;// for assembly
using System.IO;//for Stream
using System.Web.Services.Description;//for servicedescription
using System.CodeDom;//for CodeNameSpace
using System.CodeDom.Compiler;//for CodeDomProvider
/// <summary>
/// Summary description for DynamicWebService
/// </summary>
public class DynamicWebService
{
public DynamicWebService()
{
//
// TODO: Add constructor logic here
//
}

Assembly service = null;
string _url;
string _name;

public string ServiceURL
{
get
{
if (!_url.ToUpper().EndsWith("?WSDL"))
{
_url += "?WSDL";
}
return _url;
}
}

public string ServiceClassName
{
get { return _name; }
}

public DynamicWebService(string serviceURL,string serviceClassName)
{
_url = serviceURL;
_name = serviceClassName;
GetService();
}

public void GetService()
{
// 1. 使用 WebClient 下载 WSDL 信息。
WebClient web = new WebClient();
Stream stream = web.OpenRead(ServiceURL);

// 2. 创建和格式化 WSDL 文档。
ServiceDescription description = ServiceDescription.Read(stream);

// 3. 创建客户端代理代理类。
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap";// 指定访问协议。
importer.Style = ServiceDescriptionImportStyle.Client;// 生成客户端代理。
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties | System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync;
importer.AddServiceDescription(description, null, null);// 添加 WSDL 文档。

// 4. 使用 CodeDom 编译客户端代理类。
CodeNamespace nmspace = new CodeNamespace();// 为代理类添加命名空间,缺省为全局空间。
CodeCompileUnit unit = new CodeCompileUnit();
unit.Namespaces.Add(nmspace);

ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

CompilerParameters parameter = new CompilerParameters();
parameter.GenerateExecutable = false;
parameter.GenerateInMemory = true;
parameter.ReferencedAssemblies.Add("System.dll");
parameter.ReferencedAssemblies.Add("System.XML.dll");
parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
parameter.ReferencedAssemblies.Add("System.Data.dll");

CompilerResults result = provider.CompileAssemblyFromDom(parameter,unit);

if (!result.Errors.HasErrors)
{
service = result.CompiledAssembly;
}
else
{
throw new Exception("WebService have errors. ");
}
}

public object InvokeMethod(string MethodName,object[] parameters)
{
// 如果在前面为代理类添加了命名空间,此处需要将命名空间添加到类型前面。
System.Type t = service.GetType(ServiceClassName);

object o = Activator.CreateInstance(t);
MethodInfo method = t.GetMethod(MethodName);
return method.Invoke(o, parameters);
}
}

how to create a calendar in C#

I read a blog about how to create a calendar, it's simple, but i still want to past it on my blog. OK, Let's go !

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Write(DateTime.Now.Year+" . "+ DateTime.Now.Month);
CreateCalendar(DateTime.Now.Year, DateTime.Now.Month);
}
}

private void CreateCalendar(int year, int month)
{
int days = DateTime.DaysInMonth(year, month);//retrieve the days of month
DateTime dt = new DateTime(year,month,1);
int weeke = Convert.ToInt32(dt.DayOfWeek.ToString("d")); //get the week day of the first day in month
string[,] cal = new string[7,6];//store the date
for (int day = 1; day <= days; day++)
{
int x = (day + weeke - 1) % 7;
int y = (day + weeke - 1) / 7;
for (int j = 0; j < 6; j++)
{
for (int i = 0; i < 7; i++)
{
cal[x, y] = day.ToString();
}
}
}

System.Text.StringBuilder st = new System.Text.StringBuilder();
st.Append("<table cellpadding=\"0\" cellspacing=\"0\" border=\"1\">");
st.Append("<thead><th>星期天</th><th>星期一</th><th>星期二</th><th>星期三</th><th>星期四</th><th>星期五</th><th>星期六</th></thead>");
for (int i = 0; i < 6; i++)
{
st.Append("<tr>");
for (int j = 0; j < 7; j++)
{
st.Append("<td>" + cal[j, i] + "</td>");
}
st.Append("</tr>");
}
st.Append("</table>");
Response.Write(st);
Response.End();
}

}

Thursday, November 6, 2008

几种ASP.Net常用的代码

1. 打开新的窗口并传送参数: 传送参数: response.write("<script>window.open(’*.aspx?

id="+this.DropDownList1.SelectIndex+"&id1="+...+"’)</script>") 接收参数: string a =

Request.QueryString("id"); string b = Request.QueryString("id1");

Demo:
default.aspx

<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function RedirectToOtherPage()
{
// alert(document.getElementById("DropDownList1").value);
window.open("DestinationPage.aspx?value="+document.getElementById

("DropDownList1").value,"ref");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<h1>Redirect to another page and transfer value</h1>
<br /><br /><br />
<asp:DropDownList ID="DropDownList1" runat="server" Width="150">
<asp:ListItem>Kevin</asp:ListItem>
<asp:ListItem>Mary</asp:ListItem>
<asp:ListItem>Gary</asp:ListItem>
<asp:ListItem>Derek</asp:ListItem>
<asp:ListItem>John</asp:ListItem>
</asp:DropDownList> 
<asp:Button ID="Button1" runat="server" Text="TransferWithString"

OnClientClick="RedirectToOtherPage()" /> 
 
 
 
</center>
</div>
</form>
</body>
********************************
destination.aspx.cs

public partial class DestinationPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string msg = Request.QueryString["value"].ToString();
Response.Write(msg);
}
}
}

2.为按钮添加对话框 Button1.Attributes.Add("onclick","return confirm(’确认?’)");

button.attributes.add("onclick","if(confirm(’are you sure...?’)){return true;}else{return

false;}")

Demo:
default.aspx

<asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" />
<asp:HiddenField ID="Text1" runat="server" />

************************
default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Button2.Attributes.Add("onclick", "if(confirm('are you sure?')){return true;}

else{return false;}");
Button2.Attributes.Add("onclick", "if(confirm('are you sure?'))

{document.getElementById('Text1').value='kevin';}else{document.getElementById

('Text1').value='false';}");

}
protected void Button2_Click(object sender, EventArgs e)
{
if (Text1.Value == "kevin")
{
Response.Write("this is true....");
}
else
{
Response.Write("this is false...");
}
}
}

3.删除表格选定记录 int intEmpID = (int)MyDataGrid.DataKeys[e.Item.ItemIndex]; string

deleteCmd = "DELETE from Employee where emp_id = " + intEmpID.ToString()    4.删除表格记

录警告 private void DataGrid_ItemCreated(Object sender,DataGridItemEventArgs e) {  switch

(e.Item.ItemType)  {   case ListItemType.Item :   case ListItemType.AlternatingItem :

  case ListItemType.EditItem:    TableCell myTableCell;    myTableCell =

e.Item.Cells[14];    LinkButton myDeleteButton ;    myDeleteButton = (LinkButton)

myTableCell.Controls[0];    myDeleteButton.Attributes.Add("onclick","return confirm(’您

是否确定要删除这条信息’);");    break;   default:    break;  } }    5.点击表格行

链接另一页 private void grdCustomer_ItemDataBound(object sender,

System.Web.UI.WebControls.DataGridItemEventArgs e) {  //点击表格打开  if (e.Item.ItemType

== ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)   

e.Item.Attributes.Add("onclick","window.open(’Default.aspx?id=" + e.Item.Cells[0].Text + "’

);"); } 双击表格连接到另一页 在itemDataBind事件中 if(e.Item.ItemType == ListItemType.Item

|| e.Item.ItemType == ListItemType.AlternatingItem) {  string OrderItemID =e.item.cells

[1].Text;  ...  e.item.Attributes.Add("ondblclick", "location.href=’../ShippedGrid.aspx?

id=" + OrderItemID + "’"); }    双击表格打开新一页 if(e.Item.ItemType ==

ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {  string

OrderItemID =e.item.cells[1].Text;  ...  e.item.Attributes.Add("ondblclick", "open

(’../ShippedGrid.aspx?id=" + OrderItemID + "’)"); } 6.表格超连接列传递参数 <

asp:HyperLinkColumn Target="_blank" headertext="ID号" DataTextField="id"

NavigateUrl="aaa.aspx?id=’  <%# DataBinder.Eval(Container.DataItem, "数据字段1")%>’ &

name=’<%# DataBinder.Eval(Container.DataItem, "数据字段2")%>’ />    7.表格点击改变颜色

if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)

{  e.Item.Attributes.Add("onclick","this.style.backgroundColor=’#99cc00’;    

this.style.color=’buttontext’;this.style.cursor=’default’;"); } 写在DataGrid的

_ItemDataBound里 if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType ==

ListItemType.AlternatingItem) { e.Item.Attributes.Add

("onmouseover","this.style.backgroundColor=’#99cc00’;    this.style.color=’

buttontext’;this.style.cursor=’default’;"); e.Item.Attributes.Add

("onmouseout","this.style.backgroundColor=’’;this.style.color=’’;"); }    8.关于日期格式

日期格式设定 DataFormatString="{0:yyyy-MM-dd}" 我觉得应该在itembound事件中 e.items.cell["你

的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd"))    9.获取

错误信息并到指定页面 不要使用Response.Redirect,而应该使用Server.Transfer   e.g // in

global.asax protected void Application_Error(Object sender, EventArgs e) { if

(Server.GetLastError() is HttpUnhandledException) Server.Transfer("MyErrorPage.aspx"); //其

余的非HttpUnhandledException异常交给ASP.NET自己处理就okay了 :) }   Redirect会导致post-

back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面

得到出错信息并进行相应的处理    10.清空Cookie Cookie.Expires=[DateTime];

Response.Cookies("UserName").Expires = 0    11.自定义异常处理 //自定义异常处理类 using

System; using System.Diagnostics; namespace MyAppException {  /// <summary>  /// 从系统

异常类ApplicationException继承的应用程序异常处理类。  /// 自动将异常内容记录到Windows

NT/2000的应用程序日志  /// </summary>  public class

AppException:System.ApplicationException  {   public AppException()   {    if

(ApplicationConfiguration.EventLogEnabled)LogEvent("出现一个未知错误。");   }  public

AppException(string message)  {   LogEvent(message);  }  public AppException(string

message,Exception innerException)  {   LogEvent(message);   if (innerException !=

null)   {    LogEvent(innerException.Message);   }  }  //日志记录类  using

System;  using System.Configuration;  using System.Diagnostics;  using System.IO;  

using System.Text;  using System.Threading;  namespace MyEventLog  {   /// <summary>

  /// 事件日志记录类,提供事件日志记录支持   /// <remarks>   /// 定义了4个日志记录

方法 (error, warning, info, trace)   /// </remarks>   /// </summary>   public

class ApplicationLog   {    /// <summary>    /// 将错误信息记录到Win2000/NT事件日

志中    /// <param name="message">需要记录的文本信息</param>    /// </summary>

   public static void WriteError(String message)    {     WriteLog

(TraceLevel.Error, message);    }    /// <summary>    /// 将警告信息记录到

Win2000/NT事件日志中    /// <param name="message">需要记录的文本信息</param>   

 /// </summary>    public static void WriteWarning(String message)    {     

WriteLog(TraceLevel.Warning, message);      }    /// <summary>    /// 将提示信

息记录到Win2000/NT事件日志中    /// <param name="message">需要记录的文本信息</param>

   /// </summary>    public static void WriteInfo(String message)    {     

WriteLog(TraceLevel.Info, message);    }    /// <summary>    /// 将跟踪信息记录

到Win2000/NT事件日志中    /// <param name="message">需要记录的文本信息</param>   

 /// </summary>    public static void WriteTrace(String message)    {     

WriteLog(TraceLevel.Verbose, message);    }    /// <summary>    /// 格式化记录到

事件日志的文本信息格式    /// <param name="ex">需要格式化的异常对象</param>   

 /// <param name="catchInfo">异常信息标题字符串.</param>    /// <retvalue>    

/// <para>格式后的异常信息字符串,包括异常内容和跟踪堆栈.</para>    /// </retvalue

>    /// </summary>    public static String FormatException(Exception ex, String

catchInfo)    {     StringBuilder strBuilder = new StringBuilder();     if

(catchInfo != String.Empty)     {      strBuilder.Append(catchInfo).Append

("\r\n");     }     strBuilder.Append(ex.Message).Append("\r\n").Append

(ex.StackTrace);     return strBuilder.ToString();    }    /// <summary>    

/// 实际事件日志写入方法    /// <param name="level">要记录信息的级别

(error,warning,info,trace).</param>    /// <param name="messageText">要记录的文本.

</param>    /// </summary>    private static void WriteLog(TraceLevel level,

String messageText)    {     try     {      EventLogEntryType LogEntryType;

     switch (level)      {       case TraceLevel.Error:        

LogEntryType = EventLogEntryType.Error;        break;       case

TraceLevel.Warning:        LogEntryType = EventLogEntryType.Warning;        

break;       case TraceLevel.Info:        LogEntryType =

EventLogEntryType.Information;        break;       case TraceLevel.Verbose:  

      LogEntryType = EventLogEntryType.SuccessAudit;        break;      

 default:        LogEntryType = EventLogEntryType.SuccessAudit;        

break;      }      EventLog eventLog = new EventLog("Application",

ApplicationConfiguration.EventLogMachineName, ApplicationConfiguration.EventLogSourceName

);      //写入事件日志      eventLog.WriteEntry(messageText, LogEntryType);   

  }    catch {} //忽略任何异常   }  } //class ApplicationLog } 12.Panel 横向滚动,

纵向自动扩展<asp:panel style="overflow-x:scroll;overflow-y:auto;"></asp:panel>    13.

回车转换成Tab <script language="javascript" for="document" event="onkeydown">  if

(event.keyCode==13 && event.srcElement.type!=’button’ && event.srcElement.type!=’submit’ &&

    event.srcElement.type!=’reset’ && event.srcElement.type!=’’&&

event.srcElement.type!=’textarea’);    event.keyCode=9; </script> onkeydown="if

(event.keyCode==13) event.keyCode=9"    14.DataGrid超级连接列 DataNavigateUrlField="字段

名" DataNavigateUrlFormatString="http://xx/inc/delete.aspx?ID={0}"    15.DataGrid行随鼠标

变色 private void DGzf_ItemDataBound(object sender,

System.Web.UI.WebControls.DataGridItemEventArgs e) {  if (e.Item.ItemType!

=ListItemType.Header)  {   e.Item.Attributes.Add(

"onmouseout","this.style.backgroundColor=\""+e.Item.Style["BACKGROUND-COLOR"]+"\"");   

e.Item.Attributes.Add( "onmouseover","this.style.backgroundColor=\""+ "#EFF3F7"+"\"");  }

}    16.模板列 <ASP:TEMPLATECOLUMN visible="False" sortexpression="demo" headertext="ID"

> <ITEMTEMPLATE> <ASP:LABEL text=’<%# DataBinder.Eval(Container.DataItem,

"ArticleID")%>’ runat="server" width="80%" id="lblColumn" /> </ITEMTEMPLATE>

</ASP:TEMPLATECOLUMN> <ASP:TEMPLATECOLUMN headertext="选中"> <HEADERSTYLE wrap="False"

horizontalalign="Center"></HEADERSTYLE> <ITEMTEMPLATE> <ASP:CHECKBOX id="chkExport"

runat="server" /> </ITEMTEMPLATE> <EDITITEMTEMPLATE> <ASP:CHECKBOX id="chkExportON"

runat="server" enabled="true" /> </EDITITEMTEMPLATE> </ASP:TEMPLATECOLUMN>    后台代

码 protected void CheckAll_CheckedChanged(object sender, System.EventArgs e) {  //改变列的

选定,实现全选或全不选。  CheckBox chkExport ;  if( CheckAll.Checked)  {   foreach

(DataGridItem oDataGridItem in MyDataGrid.Items)   {    chkExport = (CheckBox)

oDataGridItem.FindControl("chkExport");    chkExport.Checked = true;   }  }  else  

{   foreach(DataGridItem oDataGridItem in MyDataGrid.Items)   {    chkExport =

(CheckBox)oDataGridItem.FindControl("chkExport");    chkExport.Checked = false;   }  

} }    17.数字格式化   【<%#Container.DataItem("price")%>的结果是500.0000,怎样格式化

为500.00?】 <%#Container.DataItem("price","{0:¥#,##0.00}")%> int i=123456; string

s=i.ToString("###,###.00"); 18.日期格式化   【aspx页面内:<%# DataBinder.Eval

(Container.DataItem,"Company_Ureg_Date")%>   显示为: 2004-8-11 19:44:28   我只想要:

2004-8-11 】 <%# DataBinder.Eval(Container.DataItem,"Company_Ureg_Date","{0:yyyy-M-d}")%>

  应该如何改?   【格式化日期】   取出来,一般是object((DateTime)

objectFromDB).ToString("yyyy-MM-dd");   【日期的验证表达式】   A.以下正确的输入格式:

[2004-2-29], [2004-02-29 10:29:39 pm], [2004/12/31] ^((\d{2}(([02468][048])|([13579][26]))

[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|

(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d

{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1

-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2

[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:

([0-5][0-9])\s))([AM|PM|am|pm]{2,2})))?$   B.以下正确的输入格式:[0001-12-31], [9999 09

30], [2002/03/03] ^\d{4}[\-\/\s]?((((0[13578])|(1[02]))[\-\/\s]?(([0-2][0-9])|(3[01])))|

(((0[469])|(11))[\-\/\s]?(([0-2][0-9])|(30)))|(02[\-\/\s]?[0-2][0-9]))$   【大小写转换】

HttpUtility.HtmlEncode(string); HttpUtility.HtmlDecode(string)
19.如何设定全局变量   Global.asax中   Application_Start()事件中   添加Application[属

性名] = xxx;   就是你的全局变量    20.怎样作到HyperLinkColumn生成的连接后,点击连接,

打开新窗口?   HyperLinkColumn有个属性Target,将器值设置成"_blank"即可.(Target="_blank")

  【ASPNETMENU】点击菜单项弹出新窗口   在你的menuData.xml文件的菜单项中加入

URLTarget="_blank",如: <?xml version="1.0" encoding="GB2312"?> <MenuData

ImagesBaseURL="images/"> <MenuGroup> <MenuItem Label="内参信息" URL="Infomation.aspx"

> <MenuGroup ID="BBC"> <MenuItem Label="公告信息" URL="Infomation.aspx"

URLTarget="_blank" LeftIcon="file.gif"/> <MenuItem Label="编制信息简报"

URL="NewInfo.aspx" LeftIcon="file.gif" /> ...... 21.读取DataGrid控件TextBox值 foreach

(DataGrid dgi in yourDataGrid.Items) {  TextBox tb = (TextBox)dgi.FindControl

("yourTextBoxId");  tb.Text.... }    23.在DataGrid中有3个模板列包含Textbox分别为

DG_ShuLiang (数量) DG_DanJian(单价) DG_JinE(金额)分别在5.6.7列,要求在录入数量及单价的时候

自动算出金额即:数量*单价=金额还要求录入时限制为 数值型.我如何用客户端脚本实现这个功能?   

〖思归〗 <asp:TemplateColumn HeaderText="数量"> <ItemTemplate> <asp:TextBox

id="ShuLiang" runat=’server’ Text=’<%# DataBinder.Eval(Container.DataItem,"DG_ShuLiang")%

>’ onkeyup="javascript:DoCal()" /> <asp:RegularExpressionValidator id="revS"

runat="server" ControlToValidate="ShuLiang" ErrorMessage="must be integer"

ValidationExpression="^\d+$" /> </ItemTemplate> </asp:TemplateColumn> <

asp:TemplateColumn HeaderText="单价"> <ItemTemplate> <asp:TextBox id="DanJian" runat=’

server’ Text=’<%# DataBinder.Eval(Container.DataItem,"DG_DanJian")%>’

onkeyup="javascript:DoCal()" /> <asp:RegularExpressionValidator id="revS2" runat="server"

ControlToValidate="DanJian" ErrorMessage="must be numeric" ValidationExpression="^\d+

(\.\d*)?$" /> </ItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn HeaderText="

金额"> <ItemTemplate> <asp:TextBox id="JinE" runat=’server’ Text=’<%# DataBinder.Eval

(Container.DataItem,"DG_JinE")%>’ /> </ItemTemplate> </asp:TemplateColumn><script

language="javascript"> function DoCal() {  var e = event.srcElement;  var row =

e.parentNode.parentNode;  var txts = row.all.tags("INPUT");  if (!txts.length ||

txts.length < 3)   return;  var q = txts[txts.length-3].value;  var p = txts

[txts.length-2].value;  if (isNaN(q) || isNaN(p))   return;  q = parseInt(q);  p =

parseFloat(p);  txts[txts.length-1].value = (q * p).toFixed(2); } </script> 24.datagrid

选定比较底下的行时,为什么总是刷新一下,然后就滚动到了最上面,刚才选定的行因屏幕的关系就看

不到了。page_load page.smartNavigation=true    25.在Datagrid中修改数据,当点击编辑键时,

数据出现在文本框中,怎么控制文本框的大小 ? private void DataGrid1_ItemDataBound(obj

sender,DataGridItemEventArgs e) {  for(int i=0;i<e.Item.Cells.Count-1;i++)   if

(e.Item.ItemType==ListItemType.EditType)   {    e.Item.Cells[i].Attributes.Add

("Width", "80px")   } }    26.对话框 private static string ScriptBegin = "<script

language=\"JavaScript\">"; private static string ScriptEnd = "</script>"; public static

void ConfirmMessageBox(string PageTarget,string Content) {  string ConfirmContent="var

retValue=window.confirm(’"+Content+"’);"+"if(retValue){window.location=’"+PageTarget+"’;}";

 ConfirmContent=ScriptBegin + ConfirmContent + ScriptEnd;  Page ParameterPage = (Page)

System.Web.HttpContext.Current.Handler;  ParameterPage.RegisterStartupScript

("confirm",ConfirmContent);  //Response.Write(strScript); }    27. 将时间格式化:string

aa=DateTime.Now.ToString("yyyy年MM月dd日"); 1.1 取当前年月日时分秒

currentTime=System.DateTime.Now; 1.2 取当前年 int 年= DateTime.Now.Year;    1.3 取当前月

int 月= DateTime.Now.Month;    1.4 取当前日 int 日= DateTime.Now.Day;    1.5 取当前时

int 时= DateTime.Now.Hour;    1.6 取当前分 int 分= DateTime.Now.Minute;    1.7 取当前秒

int 秒= DateTime.Now.Second;    1.8 取当前毫秒 int 毫秒= DateTime.Now.Millisecond;   

28.自定义分页代码: 先定义变量 : public static int pageCount; //总页面数 public static

int curPageIndex=1; //当前页面    下一页: if(DataGrid1.CurrentPageIndex <

(DataGrid1.PageCount - 1)) {  DataGrid1.CurrentPageIndex += 1;  curPageIndex+=1; } bind

(); // DataGrid1数据绑定函数    上一页: if(DataGrid1.CurrentPageIndex >0) {  

DataGrid1.CurrentPageIndex += 1;  curPageIndex-=1; } bind(); // DataGrid1数据绑定函数   

直接页面跳转: int a=int.Parse(JumpPage.Value.Trim());//JumpPage.Value.Trim()为跳转值 if(a

<DataGrid1.PageCount) {  this.DataGrid1.CurrentPageIndex=a; } bind(); 29.DataGrid使用:

添加删除确认: private void DataGrid1_ItemCreated(object sender,

System.Web.UI.WebControls.DataGridItemEventArgs e) {  foreach(DataGridItem di in

this.DataGrid1.Items)  {   if

(di.ItemType==ListItemType.Item||di.ItemType==ListItemType.AlternatingItem)   {    

((LinkButton)di.Cells[8].Controls[0]).Attributes.Add("onclick","return confirm(’确认删除此

项吗?’);");   }  } }    样式交替: ListItemType itemType = e.Item.ItemType; if

(itemType == ListItemType.Item ) {  e.Item.Attributes["onmouseout"] =

"javascript:this.style.backgroundColor=’#FFFFFF’;";  e.Item.Attributes["onmouseover"] =

"javascript:this.style.backgroundColor=’#d9ece1’;cursor=’hand’;" ; } else if( itemType ==

ListItemType.AlternatingItem) {  e.Item.Attributes["onmouseout"] =

"javascript:this.style.backgroundColor=’#a0d7c4’;";  e.Item.Attributes["onmouseover"] =

"javascript:this.style.backgroundColor=’#d9ece1’;cursor=’hand’;" ; }    添加一个编号列:

DataTable dt= c.ExecuteRtnTableForAccess(sqltxt); //执行sql返回的DataTable DataColumn

dc=dt.Columns.Add("number",System.Type.GetType("System.String")); for(int i=0;i<

dt.Rows.Count;i++) {  dt.Rows[i]["number"]=(i+1).ToString(); } DataGrid1.DataSource=dt;

DataGrid1.DataBind();   DataGrid1中添加一个CheckBox,页面中添加一个全选框 private void

CheckBox2_CheckedChanged(object sender, System.EventArgs e) {  foreach(DataGridItem

thisitem in DataGrid1.Items)  {   ((CheckBox)thisitem.Cells[0].Controls

[1]).Checked=CheckBox2.Checked;  } }    将当前页面中DataGrid1显示的数据全部删除 foreach

(DataGridItem thisitem in DataGrid1.Items) {  if(((CheckBox)thisitem.Cells[0].Controls

[1]).Checked)  {   string strloginid= DataGrid1.DataKeys[thisitem.ItemIndex].ToString();

  Del (strloginid); //删除函数  } }    30.当文件在不同目录下,需要获取数据库连接字符

串(如果连接字符串放在Web.config,然后在Global.asax中初始化) 在Application_Start中添加以下

代码: Application["ConnStr"]

=this.Context.Request.PhysicalApplicationPath+ConfigurationSettings.    AppSettings

["ConnStr"].ToString();    31. 变量.ToString() 字符型转换 转为字符串 12345.ToString

("n"); //生成 12,345.00 12345.ToString("C"); //生成 ¥12,345.00 12345.ToString("e"); //生成

1.234500e+004 12345.ToString("f4"); //生成 12345.0000 12345.ToString("x"); //生成 3039 (16

进制) 12345.ToString("p"); //生成 1,234,500.00%    32、变量.Substring(参数1,参数2); 截取

字串的一部分,参数1为左起始位数,参数2为截取几位。 如:string s1 = str.Substring(0,2); 33.

在自己的网站上登陆其他网站:(如果你的页面是通过嵌套方式的话,因为一个页面只能有一个FORM,这

时可以导向另外一个页面再提交登陆信息) <SCRIPT language="javascript"> <!--  function

gook(pws)  {   frm.submit();  } //--> </SCRIPT> <body leftMargin="0" topMargin="0"

onload="javascript:gook()" marginwidth="0" marginheight="0"> <form name="frm" action="

http://220.194.55.68:6080/login.php?retid=7259 " method="post"> <tr> <td> <input

id="f_user" type="hidden" size="1" name="f_user" runat="server"> <input id="f_domain"

type="hidden" size="1" name="f_domain" runat="server"> <input class="box" id="f_pass"

type="hidden" size="1" name="pwshow" runat="server"> <INPUT id="lng" type="hidden"

maxLength="20" size="1" value="5" name="lng"> <INPUT id="tem" type="hidden" size="1"

value="2" name="tem"> </td> </tr> </form>   文本框的名称必须是你要登陆的网页上的名

称,如果源码不行可以用vsniffer 看看。   下面是获取用户输入的登陆信息的代码: string name;

name=Request.QueryString["EmailName"]; try {  int a=name.IndexOf("@",0,name.Length);  

f_user.Value=name.Substring(0,a);  f_domain.Value=name.Substring(a+1,name.Length-(a+1));

 f_pass.Value=Request.QueryString["Psw"]; } catch {  Script.Alert("错误的邮箱!");  

Server.Transfer("index.aspx"); }

Wednesday, November 5, 2008

使用HttpContext的User属性来实现用户验证

HttpContext类包含了个别HTTP请求的所有特定HTTP信息。这个示例主要是讲如何使用HttpContext类中的User属性来实现用户验证!

用户验证是大部分ASP.NET WEB应用程序都要用到的,它在整个应用程序中占有很重要的地位,在.NET中,包含了很多种用户验证方式,如众所周知的PassPort认证,Windows认证,Form认证等等,可是这些都很难满足我们在实际应用中的需求,以致于很多朋友都是自己另外写代码来实现自己需要的功能,这让我们在安全性以及系统效率上要考虑很多。

实际上,ASP.NET中内置的用户验证机制功能非常强大,同时也具有非常好的的可扩展性,它能够在HttpContext对象中生成一个名为 User的属性,这个属性能让我们访问各种信息,包括用户是否已验证,用户的类型,用户名等等,我们还可以对该属性的功能进性扩展,以实现我们的要求。

分配给HttpContext.User的对象必须实现IPrincipal接口,而Iprincipal定义的属性之一是Identity,它必须实现Iidentity接口。因为,我们只要写了实现这两个接口的类,就可以在这些类中添加任何我们所需要的功能。

首先,我们创建一个项目,然后创建两个实现Iprincipal和Iidentity的类(分别放在相应的cs文件中),分另为MyIprincipal和MyIdentity

Code for MyIprincipal.cs

using System.Collections;//
///
/// Summary description for MyIprincipal
///

public class MyIprincipal : System.Security.Principal.IPrincipal
{
private System.Security.Principal.IIdentity identity;
private ArrayList roleList;

public MyIprincipal(string userID, string passwrod)
{
identity = new MyIdentity(userID, passwrod);
if (identity.IsAuthenticated)
{
roleList = new ArrayList();
roleList.Add("Admin");
}
}

public ArrayList RoleList
{
get
{
return roleList;
}
}

public System.Security.Principal.IIdentity Identity
{
get
{
return identity;
}

set
{
identity = value;
}
}

public bool IsInRole(string role)
{
return roleList.Contains(role);
}

public MyIprincipal()
{
//
// TODO: Add constructor logic here
//
}
}

*******************************

Code for MyIdentity.cs

///
/// Summary description for MyIdentity
///

public class MyIdentity : System.Security.Principal.IIdentity
{
private string userID;
private string password;

public MyIdentity( string currentUserID,string currentPassword)
{
userID = currentUserID;
password = currentPassword;
}

private bool CanPass()
{
if (userID == "kevin" && password == "kevin")
{
return true;
}
else
{
return false;
}
}

public string Name
{
get
{
return userID;
}
}

public string Password
{
get
{
return password;
}

set
{
password = value;
}
}

public bool IsAuthenticated
{
get
{
return CanPass();
}
}

public string AuthenticationType
{
get
{
return null;
}
}

public MyIdentity()
{
//
// TODO: Add constructor logic here
//
}
}

********************
Code for Default.aspx


<body>
<form id="form1" runat="server">
<div>
<center>
<table>
<tr>
<td>Name</td>
<td>
<asp:TextBox ID="txtName"

runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<asp:TextBox ID="txtPwd"

runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="btnSubmit" runat="server"

Text="Submit"
onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblMsg" Text=""

runat="server"></asp:Label>
</td>
</tr>
</table>
</center>
</div>
</form>
</body>

*************************

Code for Default.aspx.cs

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

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
MyIprincipal pri = new MyIprincipal(txtName.Text.ToString(), txtPwd.Text.ToString());
if (pri.Identity.IsAuthenticated)
{
this.lblMsg.Text = "OK";
}
else
{
lblMsg.Text = "No";
}
}
}

Tuesday, November 4, 2008

Create a discretional string(C#)

Here is a interview exam, I write it with RanDom class. OK Let's go!!

namespace StringBuildTest
{
class StringBuildT
{
string[] str = new string[] { "a", "b", "c", "d","e","f","g","h","i","j","k","l","m","n",
"o","p","q","r","s","t","u","v","w","x","y","z"};
StringBuilder SB = new StringBuilder();
Random rd = new Random();
string strOut = "";//length is 1000
public void DsiplayString()
{
for (int i = 0; i < 1000; i++)
{
SB.Append(str[(int)rd.Next(26)].ToString());
}
strOut = SB.ToString();
Console.WriteLine(strOut);
}
}

class Program
{
static void Main(string[] args)
{
StringBuildT sbt = new StringBuildT();
sbt.DsiplayString();
}
}
}

Post和Get的区别(兼谈页面间传值的方式)

I read a blog about transfer data between pages with post or get method, I think this is a good article, so past it on my blog. There's a very funny method maybe you want to focus--Context.Items
which is similar with Session.
OK,let's go!

从一个页面转向另一个页面的请求方式有两种,Post和Get.
如果从原理上来探究他们的区别,涉及到Http传输协议的细节,本文不加探究,只讨论一下表象。

所有的人都知道如下区别:
1.Post传输数据时,不需要在URL中显示出来,而Get方法要在URL中显示。
2.Post传输的数据量大,可以达到2M,而Get方法由于受到URL长度的限制,只能传递大约1024字节.
3.Post顾名思义,就是为了将数据传送到服务器段,Get就是为了从服务器段取得数据.而Get之所以也能传送数据,只是用来设计告诉服务器,你到底需要什么样的数据.Post的信息作为http请求的内容,而Get是在Http头部传输的。

我们的form表单的method方法,有两个,post,get.它在页面传值的时候的区别也就是上面提到的三点.

先来看一下post方法.
这个方法在asp时代应该跟程序员打交道很多的,因为那时候没有现在的ViewState,每个页面要恢复原来的状态,都要将页面Post给自身,然后挨个取值,重新赋值.现在这些琐碎的事情都让ViewState代劳了.所以将页面post给自身的动作,在某种程度上已经被Asp.net的程序员们忘却了,所以Post也就被大部分的忽视了,这就是技术进步的双刃剑,带来方便的同时,蒙上你的眼睛。

ViewState必须包含在<form runat="server">的窗体下,而只要包含了"runat="server""的标志,就甭想Post到其他页面中去,为什么?老盖说,我的ViewState是保存当前页面状态的,你要转到其他页面,他说,不行,**不认识的参数.如果想Post一个窗体,咋办?有四种方式可供选择.

1.在页面上新建一个form,不要加上runat="server"的标志,当然在这个窗体下的控件也就不用想用Viewstate来传值了.当在其他有runat="server"的窗体的中的按钮事件中,手动调用新建form的submit() 函数.

传送页面代码如下:

<!--html代码-->
<form id="Form1" method="post" runat="server">
<input id="btnTransfer" type="button" onclick="post();" runat="server">
<input type="text" runat="server" id="SourceData">
</form>
<form id="forPost" method="post">
<input type="text" runat="server" id="SourceData2">
</form>

<!--Script代码-->
<script language="javascript">
function post()
{
forPost.action="DestinationPage.aspx";
forPost.submit();
}
</script>


接收页面
string a=Request.Form["SourceData2"].ToString();


2.通过Session取值,在一个页面中赋值,在其他页面中共享,这个方式也被广泛应用,个人不倾向于用这种方式,我怕造成Session值的混乱无序,Session用来存一些公共的东西已经累得够呛了。

3.通过Context传值,在传送页面之前,将需要传递到其他页面的值存在Context中。示例代码如下:

传送页面

//点击某个button时触发
private void btnTransfer_ServerClick(object sender, EventArgs e)
{
Context.Items["SourceData"]=SourceData.Value;
Server.Transfer("DestinationPage.aspx");
}


接收页面

string a=Context.Items["SourceData"].ToString();


4.通过Server.Transfer的方式。
这个方式在方法三种已经用到了,不过可以在调用页面为要传递到被调用页面的值创建属性(当然可以直接将它设成public),这样就可以在其他页面访问了。

传送页面

//要传送的值
private
System.Web.UI.HtmlControls.HtmlInputText SourceData;

public string getSourceData
{
get
{
return SourceData.Value;
}
}

//传送页面
Server.Transfer("DestinationPage.aspx");


接收页面

private SourceClass sourcePage;

sourcePage=(SourceClass)Context.Handler;
string aa=sourcePage.getSourceData;


以上就是Post的在不同页面传递数据的方式了。
下面是get方法
我常用的是 传送页面

string aa=SourceData.Value;
string bb=SourceData.Value;

string url="DestinationPage.aspx?parameter1="+aa+"¶meter2="+bb;
Response.Redirect(url,false);


接收页面

string aa=Request.QueryString["parameter1"].ToString();
string bb=Request.QueryString["parameter2"].ToString();


至于 Response.Redirect(url,false)里的false都是Response.End()这个方法惹的祸,老盖说,写成false就好了,因为默认是true。我都转向其他页面了,还不让我终止原来页面的响应,BT!