在我的C#应用程序中,我需要检查当前用户是否是Administrators组的成员.它需要与Windows XP和Windows 7兼容.
目前,我使用以下代码:
bool IsAdministrator
{
get
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
Run Code Online (Sandbox Code Playgroud)
问题是如果应用程序在Windows 7上运行且UAC作为非提升管理员打开,则此方法返回false.即使应用程序作为非提升管理员运行,如何确定用户是否为管理员?
假设我的Foo班级有以下内容:
readonly IService service;
public Foo(IService service)
{
if (service == null)
throw new ArgumentNullException("service");
this.service = service;
}
public void Start()
{
service.DoStuff();
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我有一个单元测试的构造函数,我传入null来验证是否ArgumentNullException抛出了.我是否需要为我的构造函数进行第二次单元测试,在这里我传入一个有效的IService并验证是否已this.service设置(需要公共访问器)?
或者我应该依靠单元测试Start来测试此代码路径的方法?
c# constructor unit-testing dependency-injection constructor-injection
我需要使用一个我无法修改的外部组件.假设我使用该程序集中的类,如下所示:
using (ExternalWidget widget = new ExternalWidget())
{
widget.DoSomething();
}
Run Code Online (Sandbox Code Playgroud)
每次调用此代码时,都会泄漏非托管内存.ExternalWidget实现IDisposable,我已将其包装在一个using语句中,但ExternalWidget不清理其非托管资源.
由于我无法访问ExternalWidget代码,因此无法以正确的方式解决此问题.有没有其他方法可以释放所使用的内存资源ExternalWidget?
我有一个测试应用程序,允许用户从ComboBox中选择文化,并在多行TextBox中显示文化特定日期.代码如下:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Items.AddRange(
CultureInfo.GetCultures(CultureTypes.SpecificCultures));
}
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
CultureInfo selectedCulture = comboBox1.SelectedItem as CultureInfo;
DateTime currentDate = DateTime.Now;
textBox1.Text =
"My Date : " + currentDate.ToString() + Environment.NewLine +
"Culture Specific Date: " + currentDate.ToString(selectedCulture);
}
}
Run Code Online (Sandbox Code Playgroud)
我注意到如果选择"ar-SA",阿拉伯语(沙特阿拉伯),那么当我在不同的机器上运行应用程序时,我会看到不同的结果.
在Windows 7计算机上,文本框显示:
My Date : 4/11/2012 4:07:09 PM Culture Specific Date: 19/05/33 04:07:09 ?
在Windows XP计算机上,文本框显示:
My Date : 4/11/2012 4:07:09 PM Culture Specific Date: 20/05/33 04:07:09 ? …
c# ×4
.net ×3
constructor ×1
cultureinfo ×1
datetime ×1
dispose ×1
memory-leaks ×1
uac ×1
unit-testing ×1
windows-7 ×1