说到PHP环境配置与安装,通常以Apache搭载PHP配置为主,随着PHP版本不断更新,对Windows IIS平台的支持也越来越好,在Windows IIS平台上配置安装PHP环境也越来越方便。 在完成Windows 7上搭建Apache+PHP+Mysql环境搭建后,我在Windows 7 IIS7平台上对PHP5.2和PHP5.3进行了配置安装,PHP5.3之前版本在Windows IIS平台上的PHP配置方式主要以ISAPI方式进行,而PHP5.3支持IIS以FastCgi方式运行PHP,这两个PHP5版本的配置安装还是有不小的区别,下面详细介绍ISAPI和FastCgi两种方式在IIS上进行PHP配置的方法。 准备工作 在完成IIS上进行PHP5安装配置工作之前,首先需要下载PHP5.2和PHP5.3,PHP5.3以php-5.3.2-Win32-VC9-x86为准。 Windows7 IIS7安装 在进行IIS7 PHP安装配置之前,首先需要安装IIS7,Windows7默认并没有安装IIS,安装过程如下: 首先进入控制面板,点击程序和功能,再点击左侧打开和关闭Windows功能,勾选Internet Information Services可承载的Web核心,确定安装。 在完成安装后,在勾选Internet信息服务,选择安装必要的IIS功能,注意由于在配置PHP5.2和PHP5.3时,IIS7中是以ISAPI和FastCgi方式配置PHP的,所以Cgi和ISAPI扩展和ISAPI筛选器务必勾选(此处由于我首先以ISAPI方式配置PHP5.2,我没有勾选Cgi),如图: 安装IIS7 在完成Windows7 IIS7的安装后,即可在控制面板中的管理工具中看到Internet信息服务管理器选项。 ISAPI方式 第一步:php.ini配置 解压php-5.2.13-Win32-VC6-x86.zip,重命名为php52iis,将其复制到C盘根目录下,将php.ini-list文件名更改为php.ini,打开php.ini进行配置,注意extension_dir的目录指向必须准确,即 extension_dir = "C:/php52iis/ext" 另外在PHP5.2版本中没有date.timezone选项,所以无需设置。 在完成PHP5.2中php.ini的配置工作后,将其复制至C:WINDOWS目录下,同时将PHP52iis目录下的libmcrypt.dll,libmysql.dll,php5ts.dll三个文件到C:/windows/System32目录下。 第二步:以ISAPI方式配置PHP5.2 打开IIS,选择网站下的Default Web Site中的ISAPI筛选器进行PHP配置工作,即 添加ISAPI筛选器,选择PHP相应的DLL文件然后选择处理程序映射,进行添加脚本映射操作,即 在完成上述IIS7的PHP5配置后,有需要说明一下,默认IIS7下的网站,其绑定的端口为80端口,网站目录为%SystemDrive%inetpubwwwroot,如果你向我一样在此之前安装配置了Apache+PHP的环境,则需要修改默认网站绑定的端口及网站目录,如将80端口改为8080,网站目录指向D:PHPWeb。或者添加一个新网站,即先添加应用程序池,再添加一个网站。 添加默认文档 在完成新网站添加后,请确保处理程序映射中有添加的脚本映射,如果没有,请重复添加脚本映射操作即可。 第三步:重启IIS7服务器 在D:PHPWeb目录下新建一个index.php文件,内容如下 <? phpinfo(); ?> 在游览器中输入http://localhost:8080/,查看PHP5.2配置信息。 至此在Windows7 IIS7上安装配置PHP5.2就算完成了。 FastCgi方式 在Windows7 IIS7上配置PHP5.3,主要以FastCgi方式进行配置,大体上与PHP5.2的配置基本一样。首先解压php-5.3.2-Win32-VC9-x86,重命名为php53iis并将其复制到C盘根目录。 第一步:添加网站 具体添加过程请参考IIS PHP5.2的配置。 第二步:添加FastCgi模块映射 点击处理程序映射,进行添加模块操作,即 配置IIS以FastCgi方式运行PHP5.3 第三步:php.ini配置 首先将php.ini-development重命名为php.ini,并将 fastcgi.impersonate=1 默认为0,如果使用IIS,你需要开启 cgi.fix_pathinfo=1 cgi.force_redirect=0 默认开启,如果你使用IIS,可以将其关闭 其次指定extension_dir目录和date.timezone,即 extension_dir = "C:/php53iis/ext" date.timezone= Asia/Shanghai 其他PHP.INI配置与PHP5.2的配置一样,区别在于,在Windows7 IIS7上配置安装PHP时,并不需要将php.ini及其他文件复制到C:/windows及C:/windows/System32目录下,简单很多 第四步:重启IIS7服务器 同时访问http://localhost:8080/即可。 FastCGI进程意外退出如何解决? 在使用Windows7 IIS7进行PHP配置安装过程中,如果PHP配置不正确,会出现FastCGI进程意外退出出错信息,此时你可以在DOS下使用 C:php53iisphp.exe -v 进行调试查看,一般情况下会将PHP配置的错误信息报出,你只要根据此信息修改相关PHP配置即可。 至此在Windows7 IIS7平台上进行PHP5.2和PHP5.3的配置安装工作就介绍完了,应该讲随着PHP版本的提高,PHP的配置工作也越来越简单化。
View DetailsAsp.net的NamePipe机制给我们提供了很多扩展性. 使用HttpModule我们可能实现的有: 强制站点范围的Cookie策略 集中化监控与日志 编写设置与删除HTTP头 控制response输出,如删除多余空白字符 Session管理 认证与受权 下面我们来看如何实现自定义异常处理:
1 |
1: public class ErrorModule:IHttpModule |
1 |
2: { |
1 |
3: #region IHttpModule Members |
1 |
4: |
1 |
5: /// <summary> |
1 |
6: /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>. |
1 |
7: /// </summary> |
1 |
8: public void Dispose() |
1 |
9: { |
1 |
10: //do nothing |
1 |
11: } |
1 |
12: |
1 |
13: /// <summary> |
1 |
14: /// Initializes a module and prepares it to handle requests. |
1 |
15: /// </summary> |
1 |
16: /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param> |
1 |
17: public void Init(HttpApplication context) |
1 |
18: { |
1 |
19: context.Error += new EventHandler(customcontext_Error); |
1 |
20: } |
1 |
21: |
1 |
22: private void customcontext_Error(object sender, EventArgs e) |
1 |
23: { |
1 |
24: HttpContext ctx = HttpContext.Current; |
1 |
25: HttpResponse response = ctx.Response; |
1 |
26: HttpRequest request = ctx.Request; |
1 |
27: |
1 |
28: Exception exception = ctx.Server.GetLastError(); |
1 |
29: |
1 |
30: var sboutput = new StringBuilder(); |
1 |
31: sboutput.Append("Querystring:<p/>"); |
1 |
32: //Get out the query string |
1 |
33: int count = request.QueryString.Count; |
1 |
34: for (int i = 0; i < count; i++) |
1 |
35: { |
1 |
36: sboutput.AppendFormat("<br/> {0}:-- {1} ", request.QueryString.Keys[i], request.QueryString[i]); |
1 |
37: } |
1 |
38: //Get out the form collection info |
1 |
39: sboutput.Append("<p>-------------------------<p/>Form:<p/>"); |
1 |
40: count = request.Form.Count; |
1 |
41: for (int i = 0; i < count; i++) |
1 |
42: { |
1 |
43: sboutput.AppendFormat("<br/> {0}:-- {1} -- <br/>", request.Form.Keys[i], request.Form[i]); |
1 |
44: } |
1 |
45: sboutput.Append("<p>-------------------------<p/>ErrorInfo:<p/>"); |
1 |
46: sboutput.AppendFormat(@"Your request could not processed. Please press the back button on your browser and try again.<br/> |
1 |
47: If the problem persists, please contact technical support<p/> |
1 |
48: Information below is for technical support:<p/> |
1 |
49: <p/>URL:{0}<p/>Stacktrace:---<br/>{1}<p/>InnerException:<br/>{2}" |
1 |
50: , ctx.Request.Url, exception.InnerException.StackTrace, exception.InnerException); |
1 |
51: |
1 |
52: response.Write(sboutput.ToString()); |
1 |
53: |
1 |
54: // To let the page finish running we clear the error |
1 |
55: ctx.Server.ClearError(); |
1 |
56: } |
1 |
57: |
1 |
58: #endregion |
1 |
59: |
1 |
60: } |
上面的代码实现了IHttpModule接口, 实现基于HttpApplication.Error事件, 接着我们自定义输出了一些信息,包括Form,QueryString. 最后把原来的Error信息清除了,这样你看到以前那个黄页了. 这个自定义的Module可以用于调试Web应用程序使用. Web.config中配置:
1 |
<httpModules> |
1 |
<add name="ErrorLoggingModule" type="MyWeb.ErrorModule"/> |
1 |
</httpModules> |
实际开发中,我们可以做的事儿很多,对这些信息记日志,发邮件. 如下, 我们演示使用Enterprise Library 做异常处理并日志记录,部分代码如下:
1 |
1: /// <summary> |
1 |
2: /// Handles the Error event of the EntLibLogging control. |
1 |
3: /// </summary> |
1 |
4: /// <param name="sender">The source of the event.</param> |
1 |
5: /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> |
1 |
6: /// <remarks>author Petter Liu http://wintersun.cnblogs.com</remarks> |
1 |
7: private void EntLibLogging_Error(object sender, EventArgs e) |
1 |
8: { |
1 |
9: var builder = new ConfigurationSourceBuilder(); |
1 |
10: |
1 |
11: builder.ConfigureInstrumentation() |
1 |
12: .ForApplicationInstance("MyApp") |
1 |
13: .EnableLogging() |
1 |
14: .EnablePerformanceCounters(); |
1 |
15: |
1 |
16: //a single exception handling policy named MyPolicy for exceptions of type ArgumentNullException. |
1 |
17: //The handler for this exception policy will log the exception to the General category (defined in the Logging Application Block configuration) |
1 |
18: //as a warning with event ID 9000, wrap the ArgumentNullException with an InvalidOperationException, set the new exception message to MyMessage, and then re-throw the exception. |
1 |
19: builder.ConfigureExceptionHandling() |
1 |
20: .GivenPolicyWithName("MyPolicy") |
1 |
21: .ForExceptionType<ArgumentNullException>() |
1 |
22: .LogToCategory("Exception") |
1 |
23: .WithSeverity(System.Diagnostics.TraceEventType.Warning) |
1 |
24: .UsingEventId(9000) |
1 |
25: .WrapWith<InvalidOperationException>() |
1 |
26: .UsingMessage("MyMessage") |
1 |
27: .ThenNotifyRethrow(); |
1 |
28: |
1 |
29: //logging application |
1 |
30: builder.ConfigureLogging() |
1 |
31: .WithOptions |
1 |
32: .DoNotRevertImpersonation() |
1 |
33: .LogToCategoryNamed("Exception") |
1 |
34: .SendTo.FlatFile("Exception Logging File") |
1 |
35: .FormatWith(new FormatterBuilder() |
1 |
36: .TextFormatterNamed("Text Formatter") |
1 |
37: . UsingTemplate("Timestamp: {timestamp}{newline}Message: {message}{newline}Category: {category}{newline}")) |
1 |
38: .ToFile("d:\\logs\\ExceptionsLog.log") |
1 |
39: .SendTo.RollingFile("Rolling Log files") |
1 |
40: .RollAfterSize(1024) |
1 |
41: .ToFile("d:\\logs\\Rollinglog.log") |
1 |
42: .LogToCategoryNamed("General") |
1 |
43: .WithOptions.SetAsDefaultCategory() |
1 |
44: .SendTo.SharedListenerNamed("Exception Logging File"); |
1 |
45: |
1 |
46: var configSource = new DictionaryConfigurationSource(); |
1 |
47: builder.UpdateConfigurationWithReplace(configSource); |
1 |
48: EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource); |
1 |
49: |
1 |
50: var ex = HttpContext.Current.Server.GetLastError(); |
1 |
51: var em = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>(); |
1 |
52: em.HandleException(ex.InnerException, "MyPolicy"); |
1 |
53: } |
注意上面的代码, 为了运行代码您需要引用以下程序集 Enterprise Library Share Common LibraryMicrosoft.Practices.ServiceLocationLogging Application BlockException Handling Application BlockException Handling Logging Provider 这里我们使用Fluent API配置, 因此没有配置XML文件. 所以不需要Web.Config中配置任何信息. 代码中有注释. 为了测试我们使用一个PAGE故意Throw 一个ArgumentNullException. 通过Server.GetLastError()获取Exception, 这时由名为MyPolicy策略处理异常. 对于ArgumentNullException把它们记录日志到名为Exception分类中,这个日志文件位于d:\\logs\\ExceptionLog.log.实际开发你完全按照你的需要来自定义策略. 然后这个日志文件中写出的内容是这样的:
1 |
----------------------------------------Timestamp: 2011-11-12 5:57:08Message: HandlingInstanceID: a99d005d-5f8d-4613-9522-2d60efb089aaAn exception of type 'System.ArgumentNullException' occurred and was caught.----------------------------------------------------------------------------11/12/2011 13:57:08Type : System.ArgumentNullException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Message : Value cannot be null.Parameter name: Demo errorSource : MyWebHelp link : ParamName : Demo errorData : System.Collections.ListDictionaryInternalTargetSite : Void Page_Load(System.Object, System.EventArgs)Stack Trace : at MyWeb.About.Page_Load(Object sender, EventArgs e) in H:\My Project\DotNet40\TDD2010\WebHost\MyWeb\About.aspx.cs:line 14 at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)Additional Info:MachineName : USERTimeStamp : 2011-11-12 5:57:08FullName : Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35AppDomainName : 3e5cb21e-3-129655510216406250ThreadIdentity : WindowsIdentity : USER\PetterCategory: Exception |
由于我们日志模块我们配置还需要写Rollinglog.log文件,内容如下:
1 |
----------------------------------------Exception Warning: 9000 : Timestamp: 2011-11-12 5:57:08Message: HandlingInstanceID: a99d005d-5f8d-4613-9522-2d60efb089aaAn exception of type 'System.ArgumentNullException' occurred and was caught.----------------------------------------------------------------------------11/12/2011 13:57:08Type : System.ArgumentNullException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Message : Value cannot be null.Parameter name: Demo errorSource : MyWebHelp link : ParamName : Demo errorData : System.Collections.ListDictionaryInternalTargetSite : Void Page_Load(System.Object, System.EventArgs)Stack Trace : at MyWeb.About.Page_Load(Object sender, EventArgs e) in H:\My Project\DotNet40\TDD2010\WebHost\MyWeb\About.aspx.cs:line 14 at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)Additional Info:MachineName : USERTimeStamp : 2011-11-12 5:57:08FullName : Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35AppDomainName : 3e5cb21e-3-129655510216406250ThreadIdentity : WindowsIdentity : USER\PetterCategory: ExceptionPriority: 0EventId: 9000Severity: WarningTitle:Enterprise Library Exception HandlingMachine: USERApp Domain: 3e5cb21e-3-129655510216406250ProcessId: 2444Process Name: C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\WebDev.WebServer40.exeThread Name: Win32 ThreadId:2748Extended Properties: ---------------------------------------- |
1 |
你可以看到上面的EventId=9000与我们之前在CODE中配置是相同的. |
1 2 |
在开源社区有一个组件<a href="http://code.google.com/p/elmah/" target="_blank"><span style="color:#E3272D;">ELMAH</span></a>(Error Logging Modules and Handlers for ASP.NET),已实现Error处理发邮件,写DB,发送到SNS等功能. 我们随意来看下它的代码: 它就是基于IHttpModule的扩展,下面代码来ELMAH: |
1 |
1: /// <summary> |
1 |
2: /// Provides an abstract base class for <see cref="IHttpModule"/> that |
1 |
3: /// supports discovery from within partial trust environments. |
1 |
4: /// </summary> |
1 |
5: public abstract class HttpModuleBase : IHttpModule |
1 |
6: { |
1 |
7: void IHttpModule.Init(HttpApplication context) |
1 |
8: { |
1 |
9: if (context == null) |
1 |
10: throw new ArgumentNullException("context"); |
1 |
11: |
1 |
12: if (SupportDiscoverability) |
1 |
13: HttpModuleRegistry.RegisterInPartialTrust(context, this); |
1 |
14: |
1 |
15: OnInit(context); |
1 |
16: } |
1 |
17: |
1 |
18: void IHttpModule.Dispose() |
1 |
19: { |
1 |
20: OnDispose(); |
1 |
21: } |
1 |
22: |
1 |
23: /// <summary> |
1 |
24: /// Determines whether the module will be registered for discovery |
1 |
25: /// in partial trust environments or not. |
1 |
26: /// </summary> |
1 |
27: protected virtual bool SupportDiscoverability |
1 |
28: { |
1 |
29: get { return false; } |
1 |
30: } |
1 |
31: |
1 |
32: /// <summary> |
1 |
33: /// Initializes the module and prepares it to handle requests. |
1 |
34: /// </summary> |
1 |
35: protected virtual void OnInit(HttpApplication application) {} |
1 |
36: |
1 |
37: /// <summary> |
1 |
38: /// Disposes of the resources (other than memory) used by the module. |
1 |
39: /// </summary> |
1 |
40: protected virtual void OnDispose() {} |
1 |
41: } |
1 |
这是ErrorLogModule实现之前HttpModuleBase: |
1 |
1: public class ErrorLogModule : HttpModuleBase, IExceptionFiltering |
1 |
2: { |
1 |
3: public event ExceptionFilterEventHandler Filtering; |
1 |
4: public event ErrorLoggedEventHandler Logged; |
1 |
5: |
1 |
6: /// <summary> |
1 |
7: /// Initializes the module and prepares it to handle requests. |
1 |
8: /// </summary> |
1 |
9: |
1 |
10: protected override void OnInit(HttpApplication application) |
1 |
11: { |
1 |
12: if (application == null) |
1 |
13: throw new ArgumentNullException("application"); |
1 |
14: |
1 |
15: application.Error += new EventHandler(OnError); |
1 |
16: ErrorSignal.Get(application).Raised += new ErrorSignalEventHandler(OnErrorSignaled); |
1 |
17: } |
1 |
18: |
1 |
19: /// <summary> |
1 |
20: /// Gets the <see cref="ErrorLog"/> instance to which the module |
1 |
21: /// will log exceptions. |
1 |
22: /// </summary> |
1 |
23: protected virtual ErrorLog GetErrorLog(HttpContext context) |
1 |
24: { |
1 |
25: return ErrorLog.GetDefault(context); |
1 |
26: } |
1 |
27: |
1 |
28: /// <summary> |
1 |
29: /// The handler called when an unhandled exception bubbles up to |
1 |
30: /// the module. |
1 |
31: /// </summary> |
1 |
32: protected virtual void OnError(object sender, EventArgs args) |
1 |
33: { |
1 |
34: HttpApplication application = (HttpApplication) sender; |
1 |
35: LogException(application.Server.GetLastError(), application.Context); |
1 |
36: } |
1 |
37: |
1 |
38: /// <summary> |
1 |
39: /// The handler called when an exception is explicitly signaled. |
1 |
40: /// </summary> |
1 |
41: protected virtual void OnErrorSignaled(object sender, ErrorSignalEventArgs args) |
1 |
42: { |
1 |
43: LogException(args.Exception, args.Context); |
1 |
44: } |
1 |
45: |
1 |
46: /// <summary> |
1 |
47: /// Logs an exception and its context to the error log. |
1 |
48: /// </summary> |
1 |
49: protected virtual void LogException(Exception e, HttpContext context) |
1 |
50: { |
1 |
51: if (e == null) |
1 |
52: throw new ArgumentNullException("e"); |
1 |
53: |
1 |
54: // |
1 |
55: // Fire an event to check if listeners want to filter out |
1 |
56: // logging of the uncaught exception. |
1 |
57: // |
1 |
58: |
1 |
59: ExceptionFilterEventArgs args = new ExceptionFilterEventArgs(e, context); |
1 |
60: OnFiltering(args); |
1 |
61: |
1 |
62: if (args.Dismissed) |
1 |
63: return; |
1 |
64: |
1 |
65: // |
1 |
66: // Log away... |
1 |
67: // |
1 |
68: |
1 |
69: ErrorLogEntry entry = null; |
1 |
70: |
1 |
71: try |
1 |
72: { |
1 |
73: Error error = new Error(e, context); |
1 |
74: ErrorLog log = GetErrorLog(context); |
1 |
75: string id = log.Log(error); |
1 |
76: entry = new ErrorLogEntry(log, id, error); |
1 |
77: } |
1 |
78: catch (Exception localException) |
1 |
79: { |
1 |
80: // |
1 |
81: // IMPORTANT! We swallow any exception raised during the |
1 |
82: // logging and send them out to the trace . The idea |
1 |
83: // here is that logging of exceptions by itself should not |
1 |
84: // be critical to the overall operation of the application. |
1 |
85: // The bad thing is that we catch ANY kind of exception, |
1 |
86: // even system ones and potentially let them slip by. |
1 |
87: // |
1 |
88: |
1 |
89: Trace.WriteLine(localException); |
1 |
90: } |
1 |
91: |
1 |
92: if (entry != null) |
1 |
93: OnLogged(new ErrorLoggedEventArgs(entry)); |
1 |
94: } |
1 |
95: |
1 |
96: /// <summary> |
1 |
97: /// Raises the <see cref="Logged"/> event. |
1 |
98: /// </summary> |
1 |
99: protected virtual void OnLogged(ErrorLoggedEventArgs args) |
1 |
100: { |
1 |
101: ErrorLoggedEventHandler handler = Logged; |
1 |
102: |
1 |
103: if (handler != null) |
1 |
104: handler(this, args); |
1 |
105: } |
1 |
106: |
1 |
107: /// <summary> |
1 |
108: /// Raises the <see cref="Filtering"/> event. |
1 |
109: /// </summary> |
1 |
110: protected virtual void OnFiltering(ExceptionFilterEventArgs args) |
1 |
111: { |
1 |
112: ExceptionFilterEventHandler handler = Filtering; |
1 |
113: |
1 |
114: if (handler != null) |
1 |
115: handler(this, args); |
1 |
116: } |
1 |
117: |
1 |
118: /// <summary> |
1 |
119: /// Determines whether the module will be registered for discovery |
1 |
120: /// in partial trust environments or not. |
1 |
121: /// </summary> |
1 |
122: protected override bool SupportDiscoverability |
1 |
123: { |
1 |
124: get { return true; } |
1 |
125: } |
1 |
126: } |
1 |
更多的功能等待您去挖掘,我们在实际开发中按需选择.希望这篇POST对您开发有帮助. |
转自:http://www.cnblogs.com/wintersun/archive/2011/11/12/2246513.html
View Details今天分析iislog 发现一堆 “不能使用 ;文件已在使用中” fuck…. 还不少呢!Google了一下,。找到了问题所在 整站,是asp+acc 的。。。所以只给了acc的数据库权限。。数据库目录是只读的、。 解决办法 数据库目录,给webuser加上写权限。。。立刻生成了个.ldb 。。。 顺便解释下,什么是ldb ldb 文件是由共享数据库的使用者自动创建以及删除得。.LDB 文件建立并存储计算机名、用户名以及放置扩展域锁的。 .LDB 文件一般与 .MDB 同名,并且与 .MDB 文件在相同目录,在 .MDB 文件被打开时建立并锁定。 举个例子,如果你打开 c:\northwind.mdb 文件后 c:\northwind.ldb 文件会自动被建立并被锁定。 当最后一个用户关闭共享数据库时 .ldb 文件会被自动删除。但是当用户没有正常关闭数据库或者数据库已经被标记为损坏,那么 .LDB 文件不会被自动删除, 因为 .LDB 文件中存储着数据库损坏时谁正在使用该数据库。 权限问题: 记得要给予 .LDB 文件所在的文件夹一定的权限。–我就没给。。虽然可以用,但是影响了性能。。 如果你准备共享一个数据库,该 .MDB 文件应该被放置在一个用户拥有读取、写入、建立、删除权限的目录中(NTSF格式)。 即使你要求每个用户有不同的文件权限(比如,只读或者可读写),所有能够共享该数据的用户对该目录都应该拥有读取、写入、建立的权限,但是你可以分配用户对某个 .MDB 文件只拥有只读权限。 注意:如果用独占方式打开某个数据库,那么 MS JET DB 将不会建立 .LDB 文件,此时用户对目录的权限只要求有读取和写入两个权限即可。 .ldb 文件的内容: MS JET DB ENGINE 会为每个以共享方式打开数据库的使用者在 .LDB 文件中创建一个条目,每个条目的大小是 64 字节。 前面 32 字节保存计算机名,后面 32 字节保存用户名。JET DB ENGINE 支持的最大用户数是 255,因此 .LDB 文件的大小不会超过 16 KB。 当一个用户关闭一个共享数据库时,该用户在 .LDB 文件中的条目不会立即被删除,可是该条目会在下一个用户打开这个数据库时被覆盖。 这也就意味着你不能通过 .LDB 文件来唯一确定谁是某个数据库的当前使用者。 .LDB 文件的使用方法: JET DB ENGINE 使用 .LDB 文件中的信息来确定谁锁定了数据,谁正在写入被其他人锁定的数据。 如果 JET DB ENGINE 发现有其他用户的锁定冲突, 它会读取 .LDB 文件以获取计算机名与用户名谁锁定了文件或者记录。 在多数锁定冲突情况下,你会在存储记录时得到一个 “写入冲突”的提示并且取消你所做的修改。 在有些情况下你会得到如下提示: Couldn”t lock table <table name>; currently in use by user <security name> on computer <computer name>. 注意:上述关于 .LDB 文件的信息与数据库文件无关。如果一个 .LDB 文件损坏,数据库文件仍然能够工作正常。 但是写入冲突的提示消息中<security name>这个部分你可能会看见一串不知所云的文字。 参考: 在 Access 2000 中,你可以用 VBA 来输出某个数据库的所有登陆用户的信息。 关于此代码请参考: 198755 ACC2000: Checking Who Logged into Database with Jet UserRoster 转自:http://rogermmg.blog.163.com/blog/static/117472889201112343341825/
View Details1、用MySQLDriverCS连接MySQL数据库 先下载和安装MySQLDriverCS,地址: http://sourceforge.net/projects/mysqldrivercs/ 在安装文件夹下面找到MySQLDriver.dll,然后将MySQLDriver.dll添加引用到项目中 注:我下载的是版本是 MySQLDriverCS-n-EasyQueryTools-4.0.1-DotNet2.0.exe using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Odbc; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using MySQLDriverCS; namespace mysql { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { MySQLConnection conn = null; conn = new MySQLConnection(new MySQLConnectionString(“localhost”, ”inv”, ”root”, ”831025″).AsString); conn.Open(); MySQLCommand commn = new MySQLCommand(“set names gb2312″, conn); commn.ExecuteNonQuery(); string sql = ”select * from exchange “; MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn); DataSet ds = new DataSet(); mda.Fill(ds, ”table1″); this.dataGrid1.DataSource = ds.Tables["table1"]; conn.Close(); } } } 2、通过ODBC访问mysql数据库: 参考:http://www.microsoft.com/china/community/Column/63.mspx 1. 安装Microsoft ODBC.net:我安装的是mysql-connector-odbc-3.51.22-win32.msi 2. 安装MDAC 2.7或者更高版本:我安装的是mdac_typ.exe 2.7简体中文版 3. 安装MySQL的ODBC驱动程序:我安装的是 odbc_net.msi 4. 管理工具 -> 数据源ODBC –>配置DSN… 5. 解决方案管理中添加引用 Microsoft.Data.Odbc.dll(1.0.3300) 6. 代码中增加引用 using Microsoft.Data.Odbc; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; //vs2005好像没有这个命名空间,在c#2008下测试自动生成的 using System.Text; using System.Windows.Forms; using Microsoft.Data.Odbc; namespace mysql { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string MyConString = ”DRIVER={MySQL ODBC 3.51 Driver};” + ”SERVER=localhost;” + ”DATABASE=inv;” + ”UID=root;” + ”PASSWORD=831025;” + ”OPTION=3″; OdbcConnection MyConnection = new OdbcConnection(MyConString); MyConnection.Open(); Console.WriteLine(“”n success, connected successfully !”n”); string query = ”insert into test values( ‘hello’, ‘lucas’, ‘liu’)”; OdbcCommand cmd = new OdbcCommand(query, MyConnection); //处理异常:插入重复记录有异常 try{ cmd.ExecuteNonQuery(); } catch(Exception ex){ Console.WriteLine(“record duplicate.”); }finally{ […]
View Details计算机在最初只支持ASCII编码,但是后来为了支持其他语言中的字符(比如汉字)以及一些特殊字符(比如€),就引入了Unicode字符集。基于Unicode字符集的编码方式有很多,比如UTF-7、UTF-8、Unicode以及UTF-32。在Windows操作系统中,一个文本文件的前几个字节是用来指定该文件的编码方式的。如果你使用NotePad或WordPad来打开一个文本文件,你并不用担心该文件的编码方式,因为这些应用程序会先读取文件的前几个字节来确定该文件的编码方式,然后用正确的编码将文本中的每个字符显示出来。下面的图中,可以看到当用NotePad记事本保存一个文档时,可以选择的编码(Encoding)方式有哪些。 用.Net读取文本文件或写入文本文件,你都不须要担心编码方式。.Net已经将这些封装好了。在读取一个文本文件的时候,如果你已经知道文本使用的是什么编码方式,你可以指定使用哪种编码方式读取文本,否则如果不指定编码方式,.Net会读取文本的前几个字节来确定使用哪种编码方式读取文件内容的。在写入文本文件的时候,你也可以指定你想使用的编码方式。如果你没有指定编码,.Net会根据写入的文本是否含有特殊字符来决定编码方式。如果没有特殊字符,就采用ASCII编码,如果有特殊字符,就采用UTF-8编码。 (一) 读取文件 如果你要读取的文件内容不是很多,可以使用 File.ReadAllText(FilePath) 或指定编码方式 File.ReadAllText(FilePath, Encoding)的方法。它们都一次将文本内容全部读完,并返回一个包含全部文本内容的字符串 string str = File.ReadAllText(@"c:\temp\ascii.txt"); // 也可以指定编码方式 string str2 = File.ReadAllText(@"c:\temp\ascii.txt", Encoding.ASCII); 也可以使用方法File.ReadAllLines。该方法返回一个字符串数组。每一行都是一个数组元素。 string[] strs = File.ReadAllLines(@"c:\temp\ascii.txt"); // 也可以指定编码方式 string[] strs2 = File.ReadAllLines(@"c:\temp\ascii.txt", Encoding.ASCII); 当文本的内容比较大时,我们就不要将文本内容一次读完,而应该采用流(Stream)的方式来读取内容。.Net为我们封装了StreamReader类。初始化StreamReader类有很多种方式。下面我罗列出几种 StreamReader sr1 = new StreamReader(@"c:\temp\utf-8.txt"); // 同样也可以指定编码方式 StreamReader sr2 = new StreamReader(@"c:\temp\utf-8.txt", Encoding.UTF8); FileStream fs = new FileStream(@"C:\temp\utf-8.txt", FileMode.Open, FileAccess.Read, FileShare.None); StreamReader sr3 = new StreamReader(fs); StreamReader sr4 = new StreamReader(fs, Encoding.UTF8); FileInfo myFile = new FileInfo(@"C:\temp\utf-8.txt"); // OpenText 创建一个UTF-8 编码的StreamReader对象 StreamReader sr5 = myFile.OpenText(); // OpenText 创建一个UTF-8 编码的StreamReader对象 StreamReader sr6 = File.OpenText(@"C:\temp\utf-8.txt"); 初始化完成之后,你可以每次读一行,也可以每次读一个字符 ,还可以每次读几个字符,甚至也可以一次将所有内容读完。 // 读一行 string nextLine = sr.ReadLine(); // 读一个字符 int nextChar = sr.Read(); // 读100个字符 int nChars = 100; char[] charArray = new char[nChars]; int nCharsRead = sr.Read(charArray, 0, nChars); // 全部读完 string restOfStream = sr.ReadToEnd(); 使用完StreamReader之后,不要忘记关闭它: sr.Closee(); 假如我们需要一行一行的读,将整个文本文件读完,下面看一个完整的例子: StreamReader sr = File.OpenText(@"C:\temp\ascii.txt"); string nextLine; while ((nextLine = sr.ReadLine()) != null) { Console.WriteLine(nextLine); } sr.Close(); (二) 写入文件 写文件和读文件一样,如果你要写入的内容不是很多,可以使用File.WriteAllText方法来一次将内容全部写如文件。如果你要将一个字符串的内容写入文件,可以用File.WriteAllText(FilePath) 或指定编码方式 File.WriteAllText(FilePath, Encoding)方法。 string str1 = "Good Morning!"; File.WriteAllText(@"c:\temp\test\ascii.txt", str1); // 也可以指定编码方式 File.WriteAllText(@"c:\temp\test\ascii-2.txt", str1, Encoding.ASCII); 如果你有一个字符串数组,你要将每个字符串元素都写入文件中,可以用File.WriteAllLines方法: string[] strs = { "Good Morning!", "Good Afternoon!" }; File.WriteAllLines(@"c:\temp\ascii.txt", strs); File.WriteAllLines(@"c:\temp\ascii-2.txt", strs, Encoding.ASCII); 使用File.WriteAllText或File.WriteAllLines方法时,如果指定的文件路径不存在,会创建一个新文件;如果文件已经存在,则会覆盖原文件。 当要写入的内容比较多时,同样也要使用流(Stream)的方式写入。.Net封装的类是StreamWriter。初始化StreamWriter类同样有很多方式: // 如果文件不存在,创建文件; 如果存在,覆盖文件 StreamWriter sw1 = new StreamWriter(@"c:\temp\utf-8.txt"); // 也可以指定编码方式 // true 是 append text, false 为覆盖原文件 StreamWriter sw2 = new StreamWriter(@"c:\temp\utf-8.txt", true, Encoding.UTF8); // FileMode.CreateNew: 如果文件不存在,创建文件;如果文件已经存在,抛出异常 FileStream fs = new FileStream(@"C:\temp\utf-8.txt", FileMode.CreateNew, FileAccess.Write, FileShare.Read); // UTF-8 为默认编码 StreamWriter sw3 = new StreamWriter(fs); StreamWriter sw4 = new StreamWriter(fs, Encoding.UTF8); // 如果文件不存在,创建文件; 如果存在,覆盖文件 FileInfo myFile = new FileInfo(@"C:\temp\utf-8.txt"); StreamWriter sw5 = myFile.CreateText(); 初始化完成后,可以用StreamWriter对象一次写入一行,一个字符,一个字符数组,甚至一个字符数组的一部分。 // 写一个字符 sw.Write('a'); // 写一个字符数组 char[] charArray = new char[100]; // initialize these characters sw.Write(charArray); // 写一个字符数组的一部分 sw.Write(charArray, 10, 15); 同样,StreamWriter对象使用完后,不要忘记关闭。sw.Close(); 最后来看一个完整的使用StreamWriter一次写入一行的例子: FileInfo myFile = new FileInfo(@"C:\temp\utf-8.txt"); StreamWriter sw = myFile.CreateText(); string[] strs = { "早上好", "下午好" }; foreach (var s in strs) { sw.WriteLine(s); } sw.Close(); 转自:http://www.cnblogs.com/jfzhu/archive/2012/11/16/2772576.html
View Detailsopenfiledialog的使用方法 OpenFileDialog file = new OpenFileDialog(); //file.Title = “打开(Open)”;//弹出对话框的框名称 //file.Filter = “文本文件(*.txt)|*.txt”;//限制弹出对话框显示文本类型 //file.Filter = “所有文件(*.*)|*.*”;//限制弹出对话框显示文件类型 file.ShowDialog(); textBox2.Text = file.SafeFileName; ————————————— folderbrowserdialog的使用方法 FolderBrowserDialog fbd = new FolderBrowserDialog(); //fbd.SelectedPath = @”F:….”;//设置当前选择的路径 //fbd.ShowNewFolderButton = false;//是否显示新建文件夹按钮 //fbd.Description = “請選擇您將要匯出的路徑”;//描述弹出框功能 //fbd.RootFolder = Environment.SpecialFolder.Personal;//打开到个人文件夹 fbd.ShowDialog(); textBox1.Text = fbd.SelectedPath; 转自:http://blog.sina.com.cn/s/blog_7d2de80301010ak3.html
View Details给定N个整数,请使用冒泡算法按照从大到小的顺序排序 1.可对N个整数的某一段(连续的M整数)排序 2.要求具有一定的可测试性 3.C#语言 ——————-- 思路: 1.冒泡算法 2.针对部分排序 3.可测试性 先上一段最简单的代码实现冒泡算法--这里错误的使用了选择排序,请参看改进版本的修正 int[] list= new int[] {1, 2, 3, 4, 5}; for (int i=0;i<list.Length;i++) for (int j=i+1;j<list.Length;j++) { if (list[i]<list[j]) { int tmp=list[i]; list[i]=list[j]; list[j]=tmp; } } for (int i=0;i<list.Length;i++) System.Console.Write("{0}\t",list[i]); System.Console.WriteLine(""); 观看上述代码,有如下发现 1)行1,主要进行数据的初始化工作,准备数据 2)行2-11,主要实现冒泡排序算法 3)行12-14,主要是显示结果 4)行1-14,包含算法实现,调用,实现和使用糅合在一起 第一次改进: 1)数据初始化部分,其实属于调用部分,此时用的是数组,扩展性较差,这里改成List<int>,并将此步重构成函数 //初始化N个数据void Init(List<int> list,int count){ System.Random a=new Random(); for (int i=0;i<count;i++) list.Add(a.Next(100));} 这里初始化数据,主要是减少人工干预,自动产生测试数据,实际生产过程中,是需要按照实际情况,选取一些比较特殊的数据作为测试数据的. 2)冒泡排序算法实现过程部分,也可以重构成函数 //实现冒泡算法——这里错误的使用了选择排序 void Bubble(List<int> list) { for (int i=0;i<list.Count;i++) for (int j=i+1;j<list.Count;j++) { if (list[i]<list[j]) { int tmp=list[i]; list[i]=list[j]; list[j]=tmp; } } } 正确的冒泡排序为 void Bubble(List<int> list) { bool bFlag=false; for (int i=0;i<list.Count;i++) { bFlag=false; for(int j=list.Count-1-1 ;j>i-1;j--) { if (list[j]<list[j+1]) { int tmp=list[j+1]; list[j+1]=list[j]; list[j]=tmp; bFlag=true; } } if (!bFlag) break; } } 将排序的代码,重构成函数,使得算法可以非常容易进行测试,只需要将精心设计的测试数据传给函数,就可以了 3)显示结果,也是重构成函数 //显示结果 void Print(List<int> list) { for (int i=0;i<list.Count;i++) System.Console.Write("{0}\t",list[i]); System.Console.WriteLine(""); } 4)最终调用过程 public static void Main(){ List<int> list=new List<int>(); //产生测试数据 Init(list,8); //打印测试数据 Print(list); //按照从大到小的顺序排序 Bubble(list); //打印排序后的结果 Print(list); } 第二次改进: 第一次改进中,基本解决冒泡算法和可测试性的问题,但是还有一个重要问题没有解决,就是针对N个整数中的某一段连续M个数据进行排序,所以这次的改进主要集中在<冒泡排序算法实现>函数的改进 很明显,要实现这个功能,只需要,在 Bubble这个函数增加两个参数,标识出M的上下限,Bubble变成如下形式
1 |
<span style="color:#0000FF;">void</span> Bubble(List<<span style="color:#0000FF;">int</span>> list,<span style="color:#0000FF;">int</span> low,<span style="color:#0000FF;">int</span> high) |
新的实现(注意,这里我的冒泡算法的实现是不对的,我用的是选择排序,经过一个园子里的兄弟提醒,我查过资料,发现的确用错了) 选择排序(Selection sort) 首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。 void Bubble(List<int> list,int low,int high){ int iHigh= list.Count<high+1? list.Count : high+1 ; int iLow=low<0? 0 :low ; //System.Console.WriteLine("{0}\t{1}",iLow,iHigh); for (int i=iLow;i<iHigh;i++) for (int j=i+1;j<iHigh;j++) { if (list[i]<list[j])//比较不一定相邻 { int tmp=list[i]; list[i]=list[j]; list[j]=tmp; } } } 下面是更正后的冒泡排序代码 冒泡排序(BubbleSort) 依次比较相邻的两个数,将小数放在前面,大数放在后面。 static void Bubble(List<int> list,int low,int high) { int iHigh= list.Count<high+1? list.Count : high+1 ; int iLow=low<0? 0 :low ; bool bFlag=false; for (int i=iLow;i<iHigh;i++) { bFlag=false; for(int j=iHigh-1-1 ;j>i-1;j--) { if (list[j]<list[j+1])//比较相邻 { int tmp=list[j+1]; list[j+1]=list[j]; list[j]=tmp; bFlag=true; } } if (!bFlag) break; } } 并提供一个重载函数
1 |
<span style="color:#0000FF;">void</span> Bubble(List<<span style="color:#0000FF;">int</span>><span style="color:#000000;"> list)<br /></span><span style="color:#000000;">{ <span style="color:#008080;"> <br /></span></span>Bubble(list,<span style="color:#800080;">0</span><span style="color:#000000;">,list.Count-1);<br /></span>} |
调用: public static void Main() { List<int> list=new List<int>(); //产生测试数据 Init(list,8); //打印测试数据 Print(list); //按照从大到小的顺序排序,针对序号2-5的之间的数据 Bubble(list,2,5); //打印排序后的结果 Print(list); } 至此,题目要求的目的全部达到,不过还是少了点什么,下面进行第三次改进 第三次改进: 第一次改进和第二次改进的结果,还是采用面向过程的方法,第三次改进侧重与面向对象的方法,就是封装 三个主要函数中都有List<int> list参数,这个是主要数据,我们用类来封装它,如下给出完整代码 public class BubbleSort { List<int> _list; public BubbleSort() { _list=new List<int>(); } public BubbleSort(List<int> list) { _list=list; } public void Sort() { Sort( _list,0,_list.Count-1); } public void Sort(int low,int high) { Sort( _list,low,high); } //实现冒泡算法--这里错误使用选择排序,请替换为第二次改进中的正确实现 public void Sort(List<int> list,int low,int high) { //int iHigh= list.Count<low+count? list.Count : high ; int iHigh= list.Count<high+1? list.Count : high+1 ; int iLow=low<0? 0 :low ; //System.Console.WriteLine("{0}\t{1}",iLow,iHigh); for (int i=iLow;i<iHigh;i++) for (int j=i+1;j<iHigh;j++) { if (list[i]<list[j]) { int tmp=list[i]; list[i]=list[j]; list[j]=tmp; } } } //初始化N个数据 public void Init(int count) { _list.Clear(); System.Random a=new Random(); for (int i=0;i<count;i++) _list.Add(a.Next(100)); } //显示结果 public void Print(List<int> list) { Print(list,0,list.Count-1,true); } public void Print(List<int> list,int low,int high,bool IsNewLine) { int iHigh= list.Count<high+1? list.Count : high+1 ; int iLow=low<0? 0 :low ; for (int i=iLow;i<iHigh;i++) System.Console.Write("{0}\t",list[i]); if (IsNewLine) System.Console.WriteLine(""); } public void Print(int low,int high,bool IsNewLine) { Print(_list,low,high,IsNewLine); } //将排序的M个数据用红色显示 public void Print(int low,int high) { Print(0,low-1,false); System.Console.ForegroundColor=ConsoleColor.Red; Print(low,high,false); System.Console.ResetColor(); Print(high+1,_list.Count,true); } public void Print() { Print(_list); } //for test public void Test() { //产生测试数据 Init(10); //打印测试数据 Print(); //按照从大到小的顺序排序 int[] iLowHigh=new int[]{4,7}; Sort(iLowHigh[0],iLowHigh[1]); //Sort(-1,8); //Sort(0,18); //Sort(-1,18); //打印排序后的结果 //Print(); Print(iLowHigh[0],iLowHigh[1]); } } 调用代码:
1 |
<span style="color:#008080;">1</span> BubbleSort bs=<span style="color:#0000FF;">new</span><span style="color:#000000;"> BubbleSort();<br /></span><span style="color:#008080;">2</span> bs.Test(); |
View Details
WPF判断命令(Command)是否能够执行是通过ICommand.CanExecute事件,在实际程序中路由命令一般是通过CommandBinding来使命令得到实际操作代码,但是这个CanExecute事件的调用是由WPF控制的,有些时候,比如命令执行后进行一些异步耗时操作,操作完成后会影响CanExecute事件结果,但是WPF不会立即做出反应,那么这个时侯就需要手动调用CommandManager.InvalidateRequerySuggested对命令系统进行一次刷新。 比如下面这个小程序 <Window.CommandBindings> <CommandBinding Command="New" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed" /> </Window.CommandBindings> <StackPanel> <Button Command="New">执行工作</Button> <TextBlock Name="tbl" Text="等待执行"></TextBlock> </StackPanel> // // 事件执行代码 // privatevoid CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute =!finished; } privatevoid CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { System.Threading.ThreadPool.QueueUserWorkItem(dowork); } bool finished =false; void dowork(object obj) { updateUI("开始工作"); System.Threading.Thread.Sleep(1000); updateUI("工作结束"); finished =true; } void updateUI(string msg) { Dispatcher.BeginInvoke((Action)(() => tbl.Text = msg)); } 程序按钮点击后下面文字显示“工作结束”,这时按钮理应是禁用的(因为此时CanExecute结果是false),但实际上按钮没有被禁用,只有界面发生改变后(如焦点,按键变化,或者按钮再次被点击),按钮才会被禁用,因为此时WPF才调用相应的CanExecute事件。 手动调用CommandManager.InvalidateRequerySuggested就可以解决问题,注意这个函数只有在UI主线程下调用才会起作用。 void dowork(object obj) { updateUI("开始工作"); System.Threading.Thread.Sleep(1000); updateUI("工作结束"); finished =true; //手动更新 updateCommand(); } void updateCommand() { Dispatcher.BeginInvoke((Action)(() […]
View Details做过WinForm开发的都会郁闷WPF竟然没有Timer。 今天想在WPF中用Timer可是发现WPF没有Timer类,找了半天发现新增了一个 DispatcherTimer确实好用和WinForm中Timer用法相似。 —————————————————————————————————————————-- 引:银光中国 在 WPF 中不再有类似 WinForm 中的 Timer 控件,因此,需要使用 DispatcherTimer 类来实现类似 Timer 的定时执行事件,该事件使用委托方式实现。DispatcherTimer 类 在 System.Windows.Threading 下,需要 using System.Windows.Threading 命名空间。 MSDN事例: 创建了名为 dispatcherTimer 的 DispatcherTimer 对象。 事件处理程序 dispatcherTimer_Tick 被添加到 dispatcherTimer 的 Tick 事件中。 使用 TimeSpan 对象将 Interval 设置为 1 秒,并启动了计时器。
1 |
<ol class="dp-c"><li class="alt"><span><span class="comment">// DispatcherTimer setup</span><span> </span></span></li><li><span>dispatcherTimer = <span class="keyword">new</span><span> System.Windows.Threading.DispatcherTimer(); </span></span></li><li class="alt"><span>dispatcherTimer.Tick += <span class="keyword">new</span><span> EventHandler(dispatcherTimer_Tick); </span></span></li><li><span>dispatcherTimer.Interval = <span class="keyword">new</span><span> TimeSpan(0,0,1); </span></span></li><li class="alt"><span>dispatcherTimer.Start(); </span></li></ol> |
Tick 事件处理程序将更新显示当前秒数的 Label,并且它将对 CommandManager 调用 InvalidateRequerySuggested。
1 |
<ol class="dp-c"><li class="alt"><span><span class="comment">// System.Windows.Threading.DispatcherTimer.Tick handler</span><span> </span></span></li><li><span> <span class="comment">//</span><span> </span></span></li><li class="alt"><span> <span class="comment">// Updates the current seconds display and calls</span><span> </span></span></li><li><span> <span class="comment">// InvalidateRequerySuggested on the CommandManager to force </span><span> </span></span></li><li class="alt"><span> <span class="comment">// the Command to raise the CanExecuteChanged event.</span><span> </span></span></li><li><span> <span class="keyword">private</span><span> </span><span class="keyword">void</span><span> dispatcherTimer_Tick(</span><span class="keyword">object</span><span> sender, EventArgs e) </span></span></li><li class="alt"><span> { </span></li><li><span> <span class="comment">// Updating the Label which displays the current second</span><span> </span></span></li><li class="alt"><span> lblSeconds.Content = DateTime.Now.Second; </span></li><li><span> </span></li><li class="alt"><span> <span class="comment">// Forcing the CommandManager to raise the RequerySuggested event</span><span> </span></span></li><li><span> CommandManager.InvalidateRequerySuggested(); </span></li><li class="alt"><span> } </span></li></ol> |
转自:http://www.cnblogs.com/midcn/archive/2011/03/18/1987928.html
View Details
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 |
using System; using System.Configuration.Install; using System.Collections; using System.Collections.Specialized; IDictionary stateSaver = new Hashtable(); 一、安装服务: private void InstallService(IDictionary stateSaver, string filepath) { try { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController("ServiceName"); if(!ServiceIsExisted("ServiceName")) { //Install Service AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller(); myAssemblyInstaller.UseNewContext = true; myAssemblyInstaller.Path =filepath; myAssemblyInstaller.Install(stateSaver); myAssemblyInstaller.Commit(stateSaver); myAssemblyInstaller.Dispose(); //--Start Service service.Start(); } else { if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending) { service.Start(); } } } catch (Exception ex) { throw new Exception("installServiceError\n" + ex.Message); } } 或者 /// <summary> /// 安装服务 /// </summary> /// <param name="p_Path">指定服务文件路径</param> /// <param name="p_ServiceName">返回安装完成后的服务名</param> /// <returns>安装信息 正确安装返回""</returns> public static string InsertService(string p_Path, ref string p_ServiceName) { if (!File.Exists(p_Path)) return "文件不存在!"; p_ServiceName = ""; FileInfo _InsertFile = new FileInfo(p_Path); IDictionary _SavedState = new Hashtable(); try { //加载一个程序集,并运行其中的所有安装程序。 AssemblyInstaller _AssemblyInstaller = new AssemblyInstaller(p_Path, new string[] { "/LogFile=" + _InsertFile.DirectoryName + "\\" + _InsertFile.Name.Substring(0, _InsertFile.Name.Length - _InsertFile.Extension.Length) + ".log" }); _AssemblyInstaller.UseNewContext = true; _AssemblyInstaller.Install(_SavedState); _AssemblyInstaller.Commit(_SavedState); Type[] _TypeList = _AssemblyInstaller.Assembly.GetTypes();//获取安装程序集类型集合 for (int i = 0; i != _TypeList.Length; i++) { if (_TypeList[i].BaseType.FullName == "System.Configuration.Install.Installer") { //找到System.Configuration.Install.Installer 类型 object _InsertObject = System.Activator.CreateInstance(_TypeList[i]);//创建类型实列 FieldInfo[] _FieldList = _TypeList[i].GetFields(BindingFlags.NonPublic | BindingFlags.Instance); for (int z = 0; z != _FieldList.Length; z++) { if (_FieldList[z].FieldType.FullName == "System.ServiceProcess.ServiceInstaller") { object _ServiceInsert = _FieldList[z].GetValue(_InsertObject); if (_ServiceInsert != null) { p_ServiceName = ((ServiceInstaller)_ServiceInsert).ServiceName; return ""; } } } } } return ""; } catch (Exception ex) { return ex.Message; } } 二、卸载windows服务: private void UnInstallService(string filepath) { try { if (ServiceIsExisted("ServiceName")) { //UnInstall Service AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller(); myAssemblyInstaller.UseNewContext = true; myAssemblyInstaller.Path = filepath; myAssemblyInstaller.Uninstall(null); myAssemblyInstaller.Dispose(); } } catch (Exception ex) { throw new Exception("unInstallServiceError\n" + ex.Message); } } 三、判断window服务是否存在: private bool ServiceIsExisted(string serviceName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController s in services) { if (s.ServiceName == serviceName) { return true; } } return false; } 四、启动服务: private void StartService(string serviceName) { if (ServiceIsExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending) { service.Start(); for (int i = 0; i < 60; i++) { service.Refresh(); System.Threading.Thread.Sleep(1000); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { break; } if (i == 59) { throw new Exception(startServiceError.Replace("$s$", serviceName)); } } } } } 另外方法 /// <summary> /// 启动服务 /// </summary> /// <param name="serviceName"></param> /// <returns></returns> public static bool ServiceStart(string serviceName) { try { ServiceController service = new ServiceController(serviceName); if (service.Status == ServiceControllerStatus.Running) { return true; } else { TimeSpan timeout = TimeSpan.FromMilliseconds(1000 * 10); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); } } catch { return false; } return true; } 五、停止服务: private void StopService(string serviceName) { if (ServiceIsExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { service.Stop(); for (int i = 0; i < 60; i++) { service.Refresh(); System.Threading.Thread.Sleep(1000); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { break; } if (i == 59) { throw new Exception(stopServiceError.Replace("$s$", serviceName)); } } } } } 另外一方法: /// <summary> /// 停止服务 /// </summary> /// <param name="serviseName"></param> /// <returns></returns> public static bool ServiceStop(string serviseName) { try { ServiceController service = new ServiceController(serviseName); if (service.Status == ServiceControllerStatus.Stopped) { return true; } else { TimeSpan timeout = TimeSpan.FromMilliseconds(1000 * 10); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); } } catch { return false; } return true; } 六 修改服务的启动项 /// <summary> /// 修改服务的启动项 2为自动,3为手动 /// </summary> /// <param name="startType"></param> /// <param name="serviceName"></param> /// <returns></returns> public static bool ChangeServiceStartType(int startType, string serviceName) { try { RegistryKey regist = Registry.LocalMachine; RegistryKey sysReg = regist.OpenSubKey("SYSTEM"); RegistryKey currentControlSet = sysReg.OpenSubKey("CurrentControlSet"); RegistryKey services = currentControlSet.OpenSubKey("Services"); RegistryKey servicesName = services.OpenSubKey(serviceName, true); servicesName.SetValue("Start", startType); } catch (Exception ex) { return false; } return true; } 七 获取服务启动类型 /// <summary> /// 获取服务启动类型 2为自动 3为手动 4 为禁用 /// </summary> /// <param name="serviceName"></param> /// <returns></returns> public static string GetServiceStartType(string serviceName) { try { RegistryKey regist = Registry.LocalMachine; RegistryKey sysReg = regist.OpenSubKey("SYSTEM"); RegistryKey currentControlSet = sysReg.OpenSubKey("CurrentControlSet"); RegistryKey services = currentControlSet.OpenSubKey("Services"); RegistryKey servicesName = services.OpenSubKey(serviceName, true); return servicesName.GetValue("Start").ToString(); } catch (Exception ex) { return string.Empty; } } 八 验证服务是否启动 服务是否存在 /// <summary> /// 验证服务是否启动 /// </summary> /// <returns></returns> public static bool ServiceIsRunning(string serviceName) { ServiceController service = new ServiceController(serviceName); if (service.Status == ServiceControllerStatus.Running) { return true; } else { return false; } } /// <summary> /// 服务是否存在 /// </summary> /// <param name="serviceName"></param> /// <returns></returns> public static bool ServiceExist(string serviceName) { try { string m_ServiceName = serviceName; ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController s in services) { if (s.ServiceName.ToLower() == m_ServiceName.ToLower()) { return true; } } return false; } catch (Exception ex) { return false; } } 注:手动安装window服务的方法: 在“Visual Studio 2005 命令提示”窗口中,运行: 安装服务:installutil servicepath 卸除服务:installutil /u servicepath |
View Details