什么样的连接对于IIS来说是一个Inactive的连接?
IIS会回收一个Inactive的连接所占用的资源.如果一个用户请求提交了一个非常耗时的请求,然后等待响应,这个请求对应的连接是否是Inactive的?
IIS会回收一个Inactive的连接所占用的资源.如果一个用户请求提交了一个非常耗时的请求,然后等待响应,这个请求对应的连接是否是Inactive的?
WSDL不能区分两个名字一样,参数不同的web method
解决方案
1.不要这样搞
2.
[WebMethod (MessageName="HelloWorld")]
public string HelloWorld()
{
return "HelloWorld";
}
[WebMethod (MessageName="HelloWorldWithName")]
public string HelloWorld(string name)
{
return "HelloWorld " + name;
}
Namespace: System.ServiceProcess
Assembly: system.serviceprocess.dll
//—-判断本机是否运行了某项服务
ServiceController service = new ServiceController("MSSQLSERVER");
if(service.Stauts == ServiceProcess.ServiceControllerStatus.Running){…}
//—改变Service运行状态
private const string myService = "XXX";
ServiceController service = new ServiceController(myService );
if(service.Status != ServiceControllerStatus.Stopped)
{
service.Stop();
serviceControl.WaitForStatus(ServiceControllerStatus.Stopped);
}
service.Start();
//—-安装.net service
%SystemRoot%\Microsoft.NET\Framework\<Version>\InstallUtil /u /name=S1 myService.exe
%SystemRoot%\Microsoft.NET\Framework\<Version>\InstallUtil /name=S1 myService.exe
%SystemRoot%\system32\services.msc /s
//—-命令行操作
net start "myService"
net stop "myService"
Uri uri = new Uri("……….");
–Indicating whether the Uri is a universal naming convention (UNC) path.
Uri.IsUnc
–Indicating whether the specified Uri references the local host.
Uri.IsLoopback
—-代码—-
using System.Text.RegularExpressions;
string regexStr = "href\\s*=\\s*\"([^\"]*)\"";
Regex regex = new Regex (regexStr, RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(text);
foreach (Match match in matches)
{
//do sth…
}
—-正则表达式收集—-
//———————————————————–
//形如 href="http://msdn.microsoft.com/netframework/"的连接
//—-注意Group的使用\"([^\"]*)\"
//—-如果使用Groups[1],会返回 http://msdn.microsoft.com/netframework/
//—-如果使用Groups[0],会返回 href="http://msdn.microsoft.com/netframework/"
string regexStr = "href\\s*=\\s*\"([^\"]*)\""
foreach (Match match in matches)
{
string myURL = match.Groups[1];
}
–参考–
Asynchronous Pages in ASP.NET 2.0
http://msdn.microsoft.com/msdnmag/issues/05/10/WickedCode/default.aspx
讲座中的内容来源于此
//—————————————————–
Asp.net运行原理:
//—————————————————–
IIS() -> aspnet_isapi.dll ->aspnet_wp.exe
Asp.net实际是一个IIS ISAPI Extension, 处理到.aspx, .asmx的请求
C:\WINDOWS\Microsoft.NET\Framework\<version>\aspnet_isapi.dll
Asp.net的工作进程(host):
在IIS6中,当IIS运行在 worker process isolation mode 时(default),
为IIS6的工作进程w3wp.exe
如果使用ASP.NET Process Model,Asp.net的工作进程为
C:\WINDOWS\Microsoft.NET\Framework\<version>\aspnet_wp.exe()
win2003上IIS进程池中的进程host.exe,host了.net CLR
进程隔离级别在IIS5.0和IIS6.0上的区别
运行帐号的不同 ASPNET(IIS5.0),Network service(IIS6.0)
[*]如何测试web 站点的吞吐量:
IIS Stress , Application center test.
//—————————————————–
Asp.net 1.1中的异步页面实现
//—————————————————–
–参考–
Use Threads and Build Asynchronous Handlers in Your Server-Side Web Code
http://msdn.microsoft.com/msdnmag/issues/03/06/Threading/
讲座中的例子也来源于此
通常情况下,ASP.NET 会调用页面的IHttpHandler.ProcessRequest来处理用户请求,
为了实现异步,在页面的code hehid class 中实现IHttpAsyncHandler,
然后使用IHttpAsyncHandler.BeginProcessRequest来处理请求.BeginProcessRequest会
launch另外一个线程,这个线程会调用base.ProcessRequest,来完成request处理,请注意,
在这种情况下,整个request处理不是使用线程池中的线程完成的,而是在BeginProcessRequest
launch出的线程中完成的.而且BeginProcessRequest在launch一个新线程后马上返回,这样一来.
执行BeginProcessReques的线程也会被重新放到线程池中.
* AsyncDelegate.ashx的扩展名表示它是一个Handler
//—————————————————–
Asp.net 2.1中的异步页面实现
//—————————————————–
1.设置
<%@Page Async="true"…%>
2.在Page_Load中添加
AddOnPreRenderCompleteAsync(new BeginEventHander(MyBeginMethod), new EndEventHandler(MyEndMethod));
//—————————————————–
异步调用Web 服务
//—————————————————–
使用proxy上的Completed Event
proxy.FooCompleted += new FooCompletedEventHandler(OnFooCompleted);
proxy.FooAsync (…);
…
void OnFooCompleted (Object source, FooCompletedEventArgs e)
{
// Called when Foo completes
}
//———————————————
完整的代码
//———————————————
public partial class AsyncPage : System.Web.UI.Page
{
private WebRequest _request;
void Page_Load (object sender, EventArgs e)
{
AddOnPreRenderCompleteAsync (new BeginEventHandler(BeginAsyncOperation), new EndEventHandler (EndAsyncOperation));
}
IAsyncResult BeginAsyncOperation (object sender, EventArgs e, AsyncCallback cb, object state)
{
_request = WebRequest.Create("http://msdn.microsoft.com");
//—我的工作环境在一个局域网中,要运行例子,需要添加:
_request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
return _request.BeginGetResponse (cb, state);
}
void EndAsyncOperation (IAsyncResult ar)
{
string text;
using (WebResponse response = _request.EndGetResponse(ar))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
text = reader.ReadToEnd();
}
}
Regex regex = new Regex ("href\\s*=\\s*\"([^\"]*)\"", RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(text);
StringBuilder builder = new StringBuilder(1024);
foreach (Match match in matches)
{
builder.Append (match.Groups[1]);
builder.Append("<br/>");
}
Output.Text = builder.ToString ();
}
}
–相同
const和readonly的值一旦初始化则都不再可以改写.
–不同
const只能在声明时初始化;readonly既可以在声明时初始化也可以在构造器中初始化;
const隐含static,不可以再写static const;readonly则不默认static,如需要可以写static readonly;
const是编译期静态解析的常量(因此其表达式必须在编译时就可以求值);readonly则是运行期动态解析的常量;
const既可用来修饰类中的成员,也可修饰函数体内的局部变量;readonly只可以用于修饰类中的成员
方法1 使用API
Private Declare Function GetWindowsDirectory Lib "kernel32.dll" Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long
‘ Return values as C:\Windows or <Driver>:\Windows
Public Function GetTheWindowsDirectory() As String
Dim strWindowsDir As String ‘ Variable to return the path of Windows Directory
strWindowsDir = Space(250) ‘ Initilize the buffer to receive the string
GetWindowsDirectory(strWindowsDir, 250) ‘ Read the path of the windows directory
Return strWindowsDir
End Function
方法2
Environment.GetEnvironmentVariable("windir")
Cheap and interesting trick:
Convert.ToString((object)stringVar) == ""
This works because Convert.ToString(object) returns an empty string if object is null.
注意!!!
Convert.ToString(string) returns null if string is null.
(Or, if you’re using .NET 2.0 you could always use String.IsNullOrEmpty.)
其实以上的代码还可以再优化一点点:
根据FxCop的建议,我们应该使用
Convert.ToString((object)stringVar).Length==0
–Custom Numeric Format Strings
int a =100;
Console.WriteLine(a.ToString("000000"));
输出"000100"
– Standard Numeric Format Strings
比如输出16进制数 X or x Hexadecimal
Console.WriteLine(a.ToString("X"));
输出"64"
Console.WriteLine(a.ToString("X6"));
输出"000064"
– Composite Formatting
Each format item takes the following form.
{index[,alignment][:formatString]}
String.Format("hours = {0:hh}", DateTime.Now); 得到 hours = 07
String.Format("Date = {0:yy/MM/dd}", DateTime.Now); 得到 Date = 06-05-15
一个Class实现序列化需要使用SerializableAttribute() Attribute或实现ISerializable
缺省情况下,一个被SerializableAttribute标记的类型中的所有public和
private field(除过NonSerialized标记的field)都会被
序列化,如果想改变序列化的处理过程,需要实现ISerializable.
如果类型中包含pointer,将有可能无法从另一个环境中被反序列化,此时应该
用NonSerialized标记point字段
!!需要特别注意的是,Serializable 属性不能被继承。如果我们从 MyObject 派生一个新类,
此新类必须也用该属性标记,否则它不能被序列化。例如,当您试图序列化下面的类的实例时,
您将获得 SerializationException。
//========= A test object that needs to be serialized.
[Serializable()]
public class TestSimpleObject
{
public int member1;
public string member2;
public string member3;
public double member4;
// A field that is not serialized.
[NonSerialized()] public string member5;
}
}
//=========使用
//==Bin
FileStream fs = new FileStream("my.bin" , FileMode.Creat);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs , myObj);
fs.Close();
//==Soap
FileStream fs = new FileStream("my_Soap.xml" , FileMode.Creat);
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(fs , myObj);
fs.Close();
//==XML
FileStream fs = new FileStream("my.xml" , FileMode.Creat);
System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(MyType));
xmlSer.Serialize(fs , myObj);
fs.Close();
//==Deserialize
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(stream);
stream.Close();
string cfgFullPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
需要引入以下的namespace
using System.Diagnostics; //For StackTrace
using System.Reflection; //MethodInfo
Step1. Create a StackTrace
StackTrace stackTrace = new StackTrace();
大多时情况下,我们希望在exception 发生时找到引发exceptioin的代码,
此时需要使用
try
{
…
}
catch(Exception exp)
{
StackTrace stackTrace = new StackTrace(exp);
}
此时通过stackTrace.ToString() 已经可以得到大致的callstack信息.
step2. 通过StatckFrame得到代码信息
int frameCount = stackTrace.FrameCount;
for (int i = 0; i < frameCount; i++)
{
StackFrame stackFrame = stackTrace.GetFrame(i);
// Display the stack frame properties.
Console.WriteLine(" File: {0}", stackFrame.GetFileName());
Console.WriteLine(" Line Number: {0}", stackFrame.GetFileLineNumber());
Console.WriteLine(" Column Number: {0}", sf.GetFileColumnNumber());
//还有很多其他的功能GetILOffset(),GetNativeOffset()…
}
step3. 通过MethodInfo得到每一个函数的信息,用到的主要是Reflection的技巧
int frameCount = stackTrace.FrameCount;
for (int i = 0; i < frameCount; i++)
{
StackFrame stackFrame = stackTrace.GetFrame(i);
MethodInfo methodInfo = (MethodInfo)stackFrame.GetMethod();
//1 get Access
string access = string.Empty;
if (methodInfo.IsPrivate)
access = "private ";
else if (methodInfo.IsPublic)
access = "public ";
else if (methodInfo.IsFamily)
access = "protected ";
else if (methodInfo.IsAssembly)
access = "Internal ";
if (methodInfo.IsStatic)
access += "static ";
//2 method nanme
string methodName = methodInfo.Name;
//3 parameter info
ParameterInfo[] pInfos = methodInfo.GetParameters();
string paramterList = string.Empty;
for (int j = 0; j < pInfos.Length; j++)
{
paramterList += string.Format(", {0} {1}", pInfos[j].ParameterType.Name, pInfos[j].Name);
}
// Get rid of the first ", " if it exists.
if (paramterList.Length > 2)
paramterList = paramterList.Substring(2);
string output = access + methodInfo.ReturnType.Name + " "+ methodName + "(" + paramterList + ")";
Console.WriteLine(output);
}
LOCAL_MACHINE\software\Microsoft\.NetFramework
下可以看到 InstallRoot为"C:\WINDOWS\Microsoft.NET\Framework\"
LOCAL_MACHINE\software\Microsoft\.NetFramework\policy
下会有key
v1.1
v2.0
每个key下会有当前的次版本号:
如:
v1.1->4322
v2.0->50727
根据InstallRoot, primer version, sub version就可以得到.net frame work的安装路径.
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
1.首先需要下载NAntContrib,把所有的文件和NAnt的执行文件放在一起.
2.NAntContrib会调用VSS的客户端来get源代码,如果不想安装VSS,可以
只copyVSS安装路径下的SSAPI.dll 和SSUS.dll,并注册ssapi.dll,命令如下:
regsvr32 ssapi.dll
3.script
——–get:
<vssget
user="myusername"
password="mypassword"
localpath="myLocalpath"
recursive="true"
writable="true"
dbpath="myVSS\srcsafe.ini"
path="$/MyProduct"
/>
——-checkout:
<vsscheckout
user="myusername"
password="mypassword"
localpath="myLocalpath"
recursive="true"
writable="true"
dbpath="myVSS\srcsafe.ini"
path="$/MyProduct"
/>
注意localpath只能指定为本地路径
path,可以制定为vss中的路径或某个文件
——–checkin:
<vsscheckin
user="myusername"
password="mypassword"
localpath="myLocalpath"
recursive="true"
writable="false"
dbpath="myVSS\srcsafe.ini"
path="$/MyProduct"
comment="NAnt checkin"
/>
也可以直接使用vss来进行操作:
比如get:
<exec program="${vss_path}\ss.exe" commandline="GET ${path_vss} -R -I-Y -O- -GTM -GL${path_local}"
output="my.log">
</exec>
只是那一堆的参数让人有点头大.
在petshop中用到了HttpRuntime.Cache.Add()
其中第3个参数为dependencies,可以是null,说明此时无dependencie
petshop中的CacheDependency会根据web.confog来传递null,或dependencies
给HttpRuntime.Cache.Add()
这个变化被封装在DependencyFacade中
public static class DependencyFacade
{
private static readonly string path = ConfigurationManager.AppSettings[”CacheDependencyAssembly”];
//封装点
public static AggregateCacheDependency GetCategoryDependency()
{
if (!string.IsNullOrEmpty(path))
//这里又会用到Abstract Factory
return DependencyAccess.CreateCategoryDependency().GetDependency();
else
return null;
}
}
在使用时只会调用
// Create a AggregateCacheDependency object from the factory
AggregateCacheDependency cd = DependencyFacade.GetCategoryDependency();
// Store the output in the data cache, and Add the necessary AggregateCacheDependency object
HttpRuntime.Cache.Add(cacheKey, data, cd, DateTime.Now.AddHours(cacheDuration), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
不用再判断何时需要传入null.
在PetShop中,用户可以通过修改Web.Config来指定当前使用的数据访问层,
而不用修改任何代码,用到的核心技术为:Abstract Factory + config file
1.配置文件
<appSettings>
<add key=”WebDAL” value=”PetShop.SQLServerDAL”/>
<add key=”OrdersDAL” value=”PetShop.SQLServerDAL”/>
…
</appSettings>
2.在程序中有一个名为DALFactory的assemble,它只提供一个class充当Abstract Factory:
namespace PetShop.DALFactory
{
/// <summary>
/// This class is implemented following the Abstract Factory pattern to
/// create the DAL implementation
/// specified from the configuration file
/// </summary>
public sealed class DataAccess
{
//读取web.config
// Look up the DAL implementation we should be using
private static readonly string path = ConfigurationManager.AppSettings[”WebDAL”];
private static readonly string orderPath = ConfigurationManager.AppSettings[”OrdersDAL”];
private DataAccess() { }
public static PetShop.IDAL.ICategory CreateCategory()
{
string className = path + “.Category”;
return (PetShop.IDAL.ICategory)Assembly.Load(path).CreateInstance(className);
}
public static PetShop.IDAL.IInventory CreateInventory()
{
string className = path + “.Inventory”;
return (PetShop.IDAL.IInventory)Assembly.Load(path).CreateInstance(className);
}
public static PetShop.IDAL.IItem CreateItem()
{
string className = path + “.Item”;
return (PetShop.IDAL.IItem)Assembly.Load(path).CreateInstance(className);
}
public static PetShop.IDAL.IOrder CreateOrder()
{
string className = orderPath + “.Order”;
return (PetShop.IDAL.IOrder)Assembly.Load(orderPath).CreateInstance(className);
}
public static PetShop.IDAL.IProduct CreateProduct()
{
string className = path + “.Product”;
return (PetShop.IDAL.IProduct)Assembly.Load(path).CreateInstance(className);
}
}
}
以上代码逻辑基本相同:
CreateXXX先根据web.config中的信息拼接出一个classname(= config string + XXX),
然后使用CreateInstance生成实例并返回.
3. 在SQLServerDAL和OracleDAL中实现具体的class,实现对某个数据库的访问逻辑
public class Category : ICategory
{
…
}
这样的例子在PatShop中还有好几个.比如:
在web.config中可以个看到
<appSettings>
<add key=”ProfileDAL” value=”PetShop.SQLProfileDAL”/>
…
</appSettings>
代码中相应地可以找到
ProfileDALFactory
IProfileDAL
SQLProfileDAL
OracleProfileDAL
MessagingFactory
CacheDependencyFactory
Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham