小编Flo*_*ian的帖子

如何获取嵌套属性

我想检索一个PropertyInfo,这里代码:

string propertyName="Text";
PropertyInfo pi = control.GetType().GetProperty(propertyName);
Run Code Online (Sandbox Code Playgroud)

它工作正常,但如果我想检索嵌套属性,它返回null:

string propertyName="DisplayLayout.Override.RowSelectors";
PropertyInfo pi = control.GetType().GetProperty(propertyName);
Run Code Online (Sandbox Code Playgroud)

有没有办法获得嵌套属性?

最好的祝福,

弗洛里安

编辑:我现在有一个新问题,我想得到一个属性是一个数组:

string propertyName="DisplayLayout.Bands[0].Columns";
PropertyInfo pi = control.GetType().GetProperty(propertyName)
Run Code Online (Sandbox Code Playgroud)

谢谢

c# reflection

6
推荐指数
1
解决办法
7034
查看次数

语法问题使用yield return的IEnumerable <T>方法

这是我的方法:

static IEnumerable<DateTime> GetMonths(DateTime from, DateTime to)
{
    // if logs is not uptodate
    TimeSpan logsMissingTimespan = to - from;

    if (logsMissingTimespan != new TimeSpan(0))
    {
        return GetMonthsBetweenTwoDates(from, to);
    }

    return null; // Why this line ?
}

private static IEnumerable<DateTime> GetMonthsBetweenTwoDates(DateTime from, DateTime to)
{

    DateTime date = from;
    DateTime lastDate = DateTime.MaxValue;

    while (date < to)
    {
        if (lastDate.Month != date.Month)
        {
            lastDate = date;
            yield return lastDate;
        }
        date = date.AddDays(1);
    }
}
Run Code Online (Sandbox Code Playgroud)

它工作正常,但我想我可以写一些像这样清洁的东西:

static IEnumerable<DateTime> GetMonths(DateTime …
Run Code Online (Sandbox Code Playgroud)

c# yield-return

6
推荐指数
2
解决办法
1849
查看次数

是否可以从PropertyInfo获取“对象”?

在我之前提出的问题中,我想通过反思来获取一些价值。现在,我想通过反射为对象设置值。

我想写这个:

private void AppliquerColonnesPersonnalisation(Control control, Propriete propriete, PropertyInfo Info)
        {
            UltraGrid grille = (UltraGrid)control;
            SortedList<int,string> sortedOrderedColumns = new SortedList<int,string>();

            if (grille != null)
            {
                // I want to write MapPropertyInfo method 
                ColumnsCollection cols = MapPropertyInfo(Info);
Run Code Online (Sandbox Code Playgroud)

PropertyInfo包含一种ColumnsCollection。我只想将我的PropertyInfo映射到一个对象,以便在之后定义一些属性,例如:

cols[prop.Nom].Hidden = false;
Run Code Online (Sandbox Code Playgroud)

可能吗 ?

最好的祝福,

弗洛里安

编辑:我尝试了GenericTypeTea解决方案,但是我有一些问题。这是我的代码段:

        private void AppliquerColonnesPersonnalisation(Control control, Propriete propriete, PropertyInfo Info)
    {
        UltraGrid grille = (UltraGrid)control;
        ColumnsCollection c = grille.DisplayLayout.Bands[0].Columns;

                    // Throw a not match System.Reflection.TargetException
        ColumnsCollection test = Info.GetValue(c,null) as ColumnsCollection;
        SortedList<int,string> sortedOrderedColumns = new SortedList<int,string>();
Run Code Online (Sandbox Code Playgroud)

但是抛出了TargetException

c# reflection system.reflection

5
推荐指数
1
解决办法
7255
查看次数

无法将User-Defined-Data Type参数添加到我的查询中

我正在尝试将用户定义的数据类型用于C#和SQL Server 2008,但是执行command.ExecuteReader()时会引发异常。

string qyery = "SELECT * FROM Product WHERE IsAvailableProduct < @Param";
SqlCommand command = new SqlCommand(qyery, conn);
SqlParameter param = new SqlParameter("@Param", SqlDbType.Structured);

param.UdtTypeName = "MyBolean";
param.SqlDbType = SqlDbType.Structured;
param.Value = 1;

command.Parameters.Add(param);
SqlDataReader reader = command.ExecuteReader();
Run Code Online (Sandbox Code Playgroud)

引发的异常是:

Failed to convert parameter value from a Int32 to a IEnumerable``1.

我的代码有什么问题?

编辑

如果将SqlDbType更改为Udt则会出现以下异常:Specified type is not registered on the target server.System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.

如果我将DbType属性设置为Int(这是“ …

c# sql user-defined-types sql-server-2008

5
推荐指数
1
解决办法
6552
查看次数

如何使用Moq生成假货列表

我想生成一个伪造列表,而不用Moq指定伪造对象的所有属性:

var mock = Mock.Of<ICalendar>(x =>
    x.GetSchedules() == new List<ISchedule> 
    {
        // I don't want specify explicitly title and other properties
        Mock.Of<ISchedule>(y => y.Title == "fdfdf" && y.Start == DateTime.Today)
    });

List<ISchedule> s = mock.GetSchedules();
Run Code Online (Sandbox Code Playgroud)

是否可以指定“规则”而不是硬编码属性?并且可以设置我想要的项目数量吗?

谢谢。

c# moq

5
推荐指数
1
解决办法
5237
查看次数

死锁 - 锁定列而没有数据

我执行此存储过程时遇到死锁:

-- Delete transactions
delete from ADVICESEQUENCETRANSACTION
where ADVICESEQUENCETRANSACTION.id in (
  select TR.id from ADVICESEQUENCETRANSACTION TR
  inner join ACCOUNTDESCRIPTIONITEM IT on TR.ACCOUNTDESCRIPTIONITEMID = IT.id
  inner join ACCOUNTDESCRIPTION ACC on IT.ACCOUNTDESCRIPTIONID = ACC.id
  inner join RECOMMENDATIONDESCRIPTION RD on ACC.RECOMMENDATIONDESCRIPTIONID = RD.id
  inner join RECOMMENDATION REC on REC.id = RD.RECOMMENDATIONID
  inner join ADVICESEQUENCE ADV on ADV.id = REC.ADVICESEQUENCEID
  where adv.Id = @AdviceSequenceId AND (@RecommendationState is NULL OR @RecommendationState=REC.[State])
    );
Run Code Online (Sandbox Code Playgroud)

这是表的架构:

表格的架构

这是死锁图:

在此输入图像描述

你可以在这里看到死锁图的细节

因此,当我检索ressource节点的associatedobjid时,我确定它是主键和表AdviceSequenceTransaction的索引:

SELECT OBJECT_SCHEMA_NAME([object_id]), * ,
OBJECT_NAME([object_id]) 
FROM sys.partitions 
WHERE partition_id …
Run Code Online (Sandbox Code Playgroud)

sql sql-server database-deadlocks

5
推荐指数
1
解决办法
137
查看次数

将值从字符串转换为流时出错

我想序列化一个自定义对象:

public class MyCustomObject
{
    public string Name { get; set; }
    public DateTime Date { get; set; }
    public List<HttpPostedFileBase> Files { get; set; }

    public MyCustomObject()
    {
        Files = new List<HttpPostedFileBase>();
    }
}
Run Code Online (Sandbox Code Playgroud)

在json中。为此,我使用一个自定义转换器:

public class HttpPostedFileConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var stream = (Stream)value;
        using (var sr = new BinaryReader(stream))
        {
            var buffer = sr.ReadBytes((int)stream.Length);
            writer.WriteValue(Convert.ToBase64String(buffer));
        }
    }
Run Code Online (Sandbox Code Playgroud)

我使用JsonSerializerSettings序列化为json.net知道哪种类型的实现(对于HttpPostedFileBase)。

        var settings = new JsonSerializerSettings();
        settings.Converters.Add(new HttpPostedFileConverter());
        settings.TypeNameHandling = …
Run Code Online (Sandbox Code Playgroud)

c# serialization json json.net deserialization

5
推荐指数
1
解决办法
953
查看次数

如果运行速度太慢,在单元测试中测量方法的执行时间以抛出异常是一个好习惯吗?

一切都在标题中,我想知道这是不是一个好习惯:

[TestMethod]
public void Compute_Array_In_Less_1_Second()
{
    Stopwatch watcher = new Stopwatch();

    int[] A = Enumerable.Range(0, 50000).Select(i => GetRandomNumber(MIN_INT, MAX_INT)).ToArray();

    watcher.Start();
    int[] R = Program.MethodThatReturnsAnArray(A);
    watcher.Stop();

    if (watcher.ElapsedMilliseconds > 1000)
        Assert.Fail("The method runs in more 1 second");
}
Run Code Online (Sandbox Code Playgroud)

谢谢

c# unit-testing mstest

4
推荐指数
2
解决办法
2435
查看次数

我怎么能以一种不那么冗长的方式有条件地写出XML呢?

我想用C#编写一个xml文件.这是一个基本文件:

<EmployeeConfiguration>
  <Bosses>
    <Boss name="BOB">
      <Employees>
        <Employee Id="#0001" />
        <Employee Id="#0002" />
      </Employees>
    <Boss>
  </Bosses>
</EmployeeConfiguration>
Run Code Online (Sandbox Code Playgroud)

Employees如果没有Employee节点,我不想要一个节点...

我想使用XElement,但我不能因为那样......所以我使用了XmlWriter.它工作正常,但我发现编写XML非常冗长:

EmployeeConfiguration config = EmployeeConfiguration.GetConfiguration();

using (XmlWriter writer = XmlWriter.Create(_fileUri, settings))
{
  writer.WriteStartDocument();

  // <EmployeeConfiguration>
  writer.WriteStartElement("EmployeeConfiguration");

  if (config.Bosses.Count > 0)
  {
    // <Bosses>
    writer.WriteStartElement("Bosses");

    foreach (Boss b in config.Bosses)
    {
      // Boss
      writer.WriteStartElement("Boss");
      writer.WriteStartAttribute("name");
      writer.WriteString(b.Name);
      writer.WriteEndAttribute();

      if (b.Employees.Count > 0)
      {
        writer.WriteStartElement("Employees");

        foreach (Employee emp in b.Employees)
        {
            writer.WriteStartElement(Employee);
            writer.WriteStartAttribute(Id);
            writer.WriteString(emp.Id);
            writer.WriteEndAttribute();
            writer.WriteEndElement();
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

是否有另一种(和最快的)方法来编写这种xml文件?

c# xml linq-to-xml

4
推荐指数
1
解决办法
531
查看次数

依赖注入 IDbConnection SqlConnection

有时会引发此异常:

System.InvalidOperationException: 'The ConnectionString property has not been initialized.'
Run Code Online (Sandbox Code Playgroud)

我使用内置的依赖注入:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IDbConnection>(db => new SqlConnection(
                    Configuration.GetConnectionString("AppConnectionString")));

    services.AddScoped<IAppConfigurationRepository, AppConfigurationRepository>();
    services.AddScoped<IHomeworkingRequestRepository, HomeworkingRequestRepository>();
    services.AddScoped<IEmployeeRepository, EmployeeRepository>();
    services.AddScoped<IEmployeeService, EmployeeService>();
    services.AddScoped<IHomeworkingRequestService, HomeworkingRequestService>();
    services.AddMvc();
}
Run Code Online (Sandbox Code Playgroud)

之前,我已经有这个错误了。services.AddScoped<IDbConnection>我改成的代码services.AddTransient<IDbConnection>解决了这个问题。但现在我又犯了这个错误。

编辑

请查找发生异常时的代码:

public class EmployeeRepository : IEmployeeRepository
{
    private readonly IDbConnection _connection;

    public EmployeeRepository(IDbConnection connection)
    {
        _connection = connection;
    }

    public IEnumerable<Employee> GetAllActiveEmployees()
    {
        string query = @"
           SELECT
               FirstName
              ,LastName
              ,BusinessUnit
          FROM Employees";

        using (var db = _connection)
        {
            _connection.Open(); …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection asp.net-core

4
推荐指数
1
解决办法
7582
查看次数