我正试图找出一种方法来检查剃刀视图在测试中呈现的HTML.
我一直在看人们提出类似问题的帖子,但每一次,我都做不到.我得到的问题是视图引擎尝试加载.cshtml文件.它从函数中返回一个空引用异常.
[Test]
public void GetRazorViewEngine() {
var _HttpContextBaseMock = new Mock<HttpContextBase>();
var _HttpRequestMock = new Mock<HttpRequestBase>();
var _HttpResponseMock = new Mock<HttpResponseBase>();
_HttpContextBaseMock.SetupGet(x => x.Request).Returns(_HttpRequestMock.Object);
_HttpContextBaseMock.SetupGet(x => x.Response).Returns(_HttpResponseMock.Object);
var routeData = new RouteData();
routeData.Values.Add("controller", "Home");
routeData.Values.Add("action", "About");
var controller = new HomeController();
controller.ControllerContext = new
ControllerContext(_HttpContextBaseMock.Object,
routeData,
controller);
controller.Url = new UrlHelper(new RequestContext(_HttpContextBaseMock.Object, routeData),
new RouteCollection());
var razorEngine = ViewEngines.Engines
.Where(x => x.GetType() == typeof(System.Web.Mvc.RazorViewEngine))
.FirstOrDefault();
var path = "/Users/dan/Projects/Playground/MvcPlayground/Views/Home/About.cshtml";
var master = "/Users/dan/Projects/Playground/MvcPlayground/Views/Shared/_Layout.cshtml";
ViewEngineResult viewEngineResult = razorEngine.FindView(controller.ControllerContext,
path,
master, …Run Code Online (Sandbox Code Playgroud) 我正在使用MongoDB数据库.我知道当你将一个DateTime插入Mongo时,它会将它转换为UTC.但我正在进行单元测试,而我的Assert正在失败.
[TestMethod]
public void MongoDateConversion() {
DateTime beforeInsert = DateTime.Now;
DateTime afterInsert;
Car entity = new Car {
Name = "Putt putt",
LastTimestamp = beforeInsert
};
// insert 'entity'
// update 'entity' from the database
afterInsert = entity.LastTimestamp.ToLocalTime();
Assert.AreEqual(beforeInsert, afterInsert); // fails here
}
Run Code Online (Sandbox Code Playgroud)
我一定错过了一些明显的东西.当我查看调试器时,我可以看到datetime的匹配,但断言仍然说他们没有(但他们这样做):
Result Message: Assert.AreEqual failed. Expected:<5/21/2015 8:27:04 PM>. Actual:<5/21/2015 8:27:04 PM>.
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么想法?
编辑:
我想出了两个可能的解决方案,这两个解决方案都需要我记住做某事(这并不总是最好的依赖......):
一种是使用扩展方法来截断来自数据库的任何DateTime:
public static DateTime Truncate(this DateTime dateTime) {
var timeSpan = TimeSpan.FromMilliseconds(1);
var ticks = -(dateTime.Ticks % timeSpan.Ticks);
return dateTime.AddTicks(ticks);
}
Run Code Online (Sandbox Code Playgroud)
另一方面,在阅读 …
我无法找到一种从Web服务反序列化XML响应的方法.响应采用以下格式:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<providerDemographicsResponse xmlns="http://provapi.sys.test.com/provider/network/messages/providerDemographicsResponse/v1" xmlns:ns2="http://provapi.sys.test.com/provider/network/messages/providerAddress/v1" xmlns:ns3="http://provapi.sys.test.com/provider/network/messages/expandedProvider/v1" xmlns:ns4="http://provapi.sys.test.com/provider/network/messages/enrollmentDetails/v1" xmlns:ns5="http://provapi.sys.test.com/provider/network/messages/providerBusinessEntity/v1" xmlns:ns6="http://provapi.sys.test.com/provider/network/messages/providerNpoAssociation/v1" xmlns:ns7="http://provapi.sys.test.com/provider/network/messages/serviceAreaDetail/v1" xmlns:ns8="http://provapi.sys.test.com/provider/network/messages/networkProviderAddress/v1" xmlns:ns9="http://provapi.sys.test.com/provider/network/messages/delegationEntity/v1" xmlns:ns10="http://provapi.sys.test.com/provider/network/messages/providerSpecialty/v1" xmlns:ns11="http://provapi.sys.test.com/provider/network/messages/providerNpi/v1" xmlns:ns12="http://provapi.sys.test.com/provider/common/messages/metadata/v1">
<ns12:metadata>
<ns12:serviceReferenceId>test17-02-2016 16:05:47.000616</ns12:serviceReferenceId>
<ns12:limit>1</ns12:limit>
<ns12:offset>0</ns12:offset>
<ns12:total>1</ns12:total>
<ns12:outcome>
<ns12:status>200</ns12:status>
<ns12:message>Successful.</ns12:message>
<ns12:code>200</ns12:code>
<ns12:additionalDetails/>
</ns12:outcome>
</ns12:metadata>
<data>
<providerDemographics>
<cpfProviderId>0000010</cpfProviderId>
<effectiveDate>1980-01-01</effectiveDate>
<terminationDate>9999-12-31</terminationDate>
<provider-under-review-indicator>N</provider-under-review-indicator>
<providerTypeDescription>Healthcare Organization</providerTypeDescription>
</providerDemographics>
<providerDemographics>
<cpfProviderId>0000010</cpfProviderId>
<effectiveDate>1980-01-01</effectiveDate>
<terminationDate>9999-12-31</terminationDate>
<provider-under-review-indicator>N</provider-under-review-indicator>
<providerTypeDescription>Healthcare Organization</providerTypeDescription>
</providerDemographics>
</data>
</providerDemographicsResponse>
Run Code Online (Sandbox Code Playgroud)
我有这个类来获取XML底部的providerDemographics列表:
public class ProviderDemographics {
[XmlAttribute(AttributeName = "cpfProviderId")]
public int CpfProviderId { get; set; }
[XmlAttribute(AttributeName = "effectiveDate")]
public DateTime EffectiveDate { get; set; }
[XmlAttribute(AttributeName = "terminationDate")]
public DateTime …Run Code Online (Sandbox Code Playgroud) 我知道在使用模型优先开发时,您可以使用t4模板生成的部分类来添加元数据.例如
public partial class Address
{
public int Id { get; set; }
public string Street1 { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后在一个单独的文件中,我做:
[MetadataType(typeof(AddressMetadata))]
public partial class Address {
}
internal sealed class AddressMetadata {
[Display(Name = "Street")]
public string Street1 { get; set; }
[Display(Name = "Street (cont.)")]
public string Street2 { …Run Code Online (Sandbox Code Playgroud) 使用以下DataTable:
Dim d As New DataTable()
d.Columns.Add("Product", GetType(System.String))
d.Columns.Add("Value", GetType(System.Double))
d.Rows.Add(New Object() {"OAP1", 100.0})
d.Rows.Add(New Object() {"EPP4", 100})
d.Rows.Add(New Object() {"OAP1", 150.25})
d.Rows.Add(New Object() {"OAPIN", 200.0})
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用LINQ来识别是否存在多种类型的产品.在SQL中,这将工作如下:
SELECT Product FROM SOME_TABLE HAVING COUNT(*) > 1
Run Code Online (Sandbox Code Playgroud)
我不能为我的生活弄明白如何在LINQ中做到这一点.我跟随的人做了这样的事:
Dim q = From row In d.AsEnumerable()
Group row By New { column1 = row("Product"), column2 = row("Value") }
Into grp
Where grp.Count() > 1
Select row
For Each item In q
' 'q' is not declared. It may be inaccessible due to its …Run Code Online (Sandbox Code Playgroud) 今天去Visual Studio 2010 Pro新建一个C++项目,然后编译,出现以下两个错误:
1 error : Required file "" is missing. C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\Win32\Microsoft.Cpp.Win32.Targets 62 6 Test
2 IntelliSense: cannot open source file "SDKDDKVer.h" c:\users\champad\documents\applications\leadinghedge-rebuild\leadinghedge\test\targetver.h 8 1 Test
Run Code Online (Sandbox Code Playgroud)
第一个错误指向Microsoft.Cpp.Win32.Targets文件中的这个标签:
<CL Condition="'%(ClCompile.PrecompiledHeader)' == 'Create' and '%(ClCompile.ExcludedFromBuild)'!='true'"
BuildingInIDE ="$(BuildingInsideVisualStudio)"
Sources ="@(ClCompile)"
AdditionalIncludeDirectories ="%(ClCompile.AdditionalIncludeDirectories)"
AdditionalOptions ="%(ClCompile.AdditionalOptions)"
AdditionalUsingDirectories ="%(ClCompile.AdditionalUsingDirectories)"
AssemblerListingLocation ="%(ClCompile.AssemblerListingLocation)"
AssemblerOutput ="%(ClCompile.AssemblerOutput)"
BasicRuntimeChecks ="%(ClCompile.BasicRuntimeChecks)"
BrowseInformation ="%(ClCompile.BrowseInformation)"
BrowseInformationFile ="%(ClCompile.BrowseInformationFile)"
BufferSecurityCheck ="%(ClCompile.BufferSecurityCheck)"
CallingConvention ="%(ClCompile.CallingConvention)"
CompileAsManaged ="%(ClCompile.CompileAsManaged)"
CompileAs ="%(ClCompile.CompileAs)"
DebugInformationFormat ="%(ClCompile.DebugInformationFormat)"
DisableLanguageExtensions ="%(ClCompile.DisableLanguageExtensions)"
DisableSpecificWarnings ="%(ClCompile.DisableSpecificWarnings)"
EnableEnhancedInstructionSet ="%(ClCompile.EnableEnhancedInstructionSet)"
EnableFiberSafeOptimizations ="%(ClCompile.EnableFiberSafeOptimizations)"
EnablePREfast ="%(ClCompile.EnablePREfast)"
ErrorReporting ="%(ClCompile.ErrorReporting)" …Run Code Online (Sandbox Code Playgroud) 我有一个在 a 内ItemsControl显示一堆 的。这非常有效,除非我有一堆用户控件,然后溢出会呈现在屏幕外,并且我无法访问它。我的目标是让 WrapPanel 水平换行,但是一旦控件离开屏幕,就会显示滚动条,这似乎对我不起作用。UserControlWrapPanel
<ItemsControl ItemsSource="{Binding Servers, Mode=OneWay}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="1" Margin="5,5,5,5">
<local:ServerControl DataContext="{Binding }" /> <!-- The actual UserControl -->
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
当应用程序第一次启动时,这就是它的样子。如果应该查看 14 个盒子,您将看不到什么。WrapPanel 正在执行其工作,但它被渲染到窗口边界之外。
这显示了所有用户控件,但我必须扩展窗口才能看到它们。
任何帮助将不胜感激。
完整的 XAML:
<Window x:Class="ServerMonitor.Wpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ServerMonitor.Wpf"
xmlns:models="clr-namespace:ServerMonitor.Wpf.Models"
xmlns:System="clr-namespace:System;assembly=mscorlib"
Title="Leading Hedge Server Monitor" Height="350" Width="800">
<Window.DataContext>
<models:MainWindowViewModel>
<models:MainWindowViewModel.MachineNames>
<!-- Test Servers -->
<System:String>T009</System:String>
<System:String>T010</System:String>
<System:String>T011</System:String>
<System:String>T012</System:String>
</models:MainWindowViewModel.MachineNames>
</models:MainWindowViewModel>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition …Run Code Online (Sandbox Code Playgroud) 我试图找出如何拉嵌嵌套的XML元素并将其转换为SQL中的表结果.WorkItem总是有一个组,但组字段可以嵌套N次.是否有一种简单的方法可以将字段拉出XML字段,如下所示:
declare @xml XML = '
<WorkItem>
<Group Name="Base" >
<Field FieldId="361" Name="Assigned To" />
<Field FieldId="362" Name="Stuff" />
<Group Name="Detail">
<Field FieldId="363" Name="Assigned To 2" />
</Group>
</Group>
</WorkItem>'
declare @handle int
declare @status int
exec @status = sp_xml_preparedocument @handle output, @xml
select *
from openxml(@handle, 'WorkItem/Group/Field')
with (
FieldId int,
Name varchar(max)
)
exec sp_xml_removedocument @handle
Run Code Online (Sandbox Code Playgroud)
我得到了什么:
361,Assigned To
362,Stuff
Run Code Online (Sandbox Code Playgroud)
我期待的是:
361,Assigned To
362,Stuff
363,Assigned To 2
Run Code Online (Sandbox Code Playgroud)
谢谢!
我正在使用 .NET Core 3.1 并尝试设置运行状况检查,但遇到了一个奇怪的问题,需要一些帮助。
当我访问基本运行状况检查 URL (https://localhost:5001/hc) 时,我得到以下信息:
{
"status": "Healthy",
"errors": [
{
"key": "AssessmentContext",
"value": "Healthy"
}
]
}
Run Code Online (Sandbox Code Playgroud)
看起来不错!然而,当我尝试进入用户界面时,它说该应用程序不健康。
因此,它正确地提取了端点名称,但没有正确注册。
我的startup.cs 文件如下所示:
public void ConfigureServices(IServiceCollection services) {
...
services
.AddHealthChecks()
.AddDbContextCheck<AssessmentContext>();
services.AddHealthChecksUI(opt => {
opt.SetEvaluationTimeInSeconds(30);
opt.MaximumHistoryEntriesPerEndpoint(60);
opt.AddHealthCheckEndpoint(name: "app", uri: "~/hc");
}).AddInMemoryStorage();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
...
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/hc", new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse,
});
endpoints.MapHealthChecksUI(opt => {
opt.UseRelativeApiPath = false;
opt.UseRelativeResourcesPath = false;
opt.AsideMenuOpened …Run Code Online (Sandbox Code Playgroud) 我正在使用OleDb填充数据表。我正在尝试使用参数化查询,但它似乎不适用于OleDbDataAdapter。有人有什么建议吗?
cmd.CommandText = "SELECT A,B,C,D FROM someTable WHERE A=@A AND D BETWEEN @D1 AND @D2";
cmd.Parameters.Add("@A", OleDbType.VarChar).Value = "1234567";
cmd.Parameters.Add("@D1", OleDbType.DBDate).Value = "02/01/2011";
cmd.Parameters.Add("@D2", OleDbType.DBDate).Value = "01/31/2012";
A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
System.Data.OleDb.OleDbException (0x80040E11): [DB2] SQL0206N "@A" is not valid in the context where it is used. SQLSTATE=42703
Run Code Online (Sandbox Code Playgroud) 我没有为OleDbConnection,MySqlConnection,OdbcConnection和Db2Connection维护一些不同的数据库访问层,而是试图找出一种使用泛型的方法.但是,当我尝试编译代码时出现错误,当我尝试访问类的方法或属性时出错.
public class DatabaseConnector<CONNECTION> {
private CONNECTION connection = default(CONNECTION);
public bool IsConnected {
get {
return (
this.connection != null &&
// error on connection.State on the following two lines
this.connection.State != System.Data.ConnectionState.Closed &&
this.connection.State != System.Data.ConnectionState.Broken
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法解决?或者也许是另一个可以处理许多版本的类?
c# ×8
linq ×2
oledb ×2
xml ×2
asp.net-core ×1
asp.net-mvc ×1
c++ ×1
datatable ×1
generics ×1
health-check ×1
itemscontrol ×1
mongodb ×1
msbuild ×1
razor ×1
scrollviewer ×1
soap ×1
sql ×1
sql-server ×1
unit-testing ×1
vb.net ×1
wpf ×1
wrappanel ×1
xamarin ×1