小编Jim*_*Jim的帖子

是否有基于任务的System.Threading.Timer替换?

我是.Net 4.0的任务的新手,我无法找到我认为基于任务的替换或实现定时器,例如定期任务.有这样的事吗?

更新 我提出了我认为是我的需求的解决方案,即将"计时器"功能包装在具有子任务的任务中,所有任务都利用CancellationToken并返回任务以便能够参与进一步的任务步骤.

public static Task StartPeriodicTask(Action action, int intervalInMilliseconds, int delayInMilliseconds, CancellationToken cancelToken)
{ 
    Action wrapperAction = () =>
    {
        if (cancelToken.IsCancellationRequested) { return; }

        action();
    };

    Action mainAction = () =>
    {
        TaskCreationOptions attachedToParent = TaskCreationOptions.AttachedToParent;

        if (cancelToken.IsCancellationRequested) { return; }

        if (delayInMilliseconds > 0)
            Thread.Sleep(delayInMilliseconds);

        while (true)
        {
            if (cancelToken.IsCancellationRequested) { break; }

            Task.Factory.StartNew(wrapperAction, cancelToken, attachedToParent, TaskScheduler.Current);

            if (cancelToken.IsCancellationRequested || intervalInMilliseconds == Timeout.Infinite) { break; }

            Thread.Sleep(intervalInMilliseconds);
        }
    };

    return Task.Factory.StartNew(mainAction, cancelToken);
}      
Run Code Online (Sandbox Code Playgroud)

c# timeout timer .net-4.0 task-parallel-library

84
推荐指数
5
解决办法
6万
查看次数

AppFabric for Windows Server仍在开发中吗?

根据您的目标是Windows Azure或Windows Server,在发现缓存API严重不同之后,我担心微软不会继续为Windows Server开发AppFabric.有谁知道AppFabric for Windows Server是否仍然受支持/开发?

azure appfabric appfabric-cache

12
推荐指数
3
解决办法
1848
查看次数

带有.Net Core 2.1的HttpClient挂起

鉴于以下.Net Core 2.1控制台应用...

using System;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;

namespace TestHttpClient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                    

                    string url = "https://jsonplaceholder.typicode.com/posts/1";
                    var response = httpClient.GetAsync(url).Result;
                    string jsonResult = response.Content.ReadAsStringAsync().Result;   
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

对GetAsync的调用挂起抛出异常,并显示以下消息:

System.Net.Http.HttpRequestException:连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机无法响应---> System.Net.Sockets.SocketException:A连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机无法响应

但是,切换到.Net Core 2.0,它工作正常......

注意

我尝试过使用:

HttpClientFactory -> Same result
WebRequest        -> Same result
Run Code Online (Sandbox Code Playgroud)

思考?

更新1 当不在公司网络上时,这可能意味着可能意味着代理行为的改变.然而,core2.0仍然可以工作,所以试图找到差异.

更新2 看起来像一个错误被引入并报告...

https://github.com/dotnet/corefx/issues/30166#issuecomment-395489603

.net c# .net-core asp.net-core-2.1 .net-core-2.1

11
推荐指数
2
解决办法
9767
查看次数

为什么使用匿名类型工作并使用不在GroupBy中的显式类型?

我有一个问题,我希望组类型强类型,但如果我这样做不正确分组.看下面的代码......

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication35
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Foo> foos = new List<Foo>();
            foos.Add(new Foo() { Key = "Test" });
            foos.Add(new Foo() { Key = "Test" });
            foos.Add(new Foo() { Key = "Test" });

            var groups = foos.GroupBy<Foo, dynamic>(entry => new
            {
                GroupKey = entry.Key
            });

            Console.WriteLine(groups.Count());

            groups = foos.GroupBy<Foo, dynamic>(entry => new GroupingKey()
            {
                GroupKey = entry.Key
            });

            Console.WriteLine(groups.Count());

        }

        public class Foo
        {
            public string Key { get; …
Run Code Online (Sandbox Code Playgroud)

c# linq linq-to-objects c#-4.0

9
推荐指数
1
解决办法
528
查看次数

如何找到未使用PrincipalSearcher设置属性的UserPrincipal?

我正在尝试在未设置属性的AD LDS(ADAM)实例中搜索用户,例如,"company"属性未设置为ADAM存储(或AD)中的值.

当我使用PrincipalSearcherUserPrincipal定义AdvancedSearchFilters对象的自定义和自定义时,我收到错误:

An unhandled exception of type 'System.ArgumentException' occurred in System.DirectoryServices.dll

Additional information: The (&(objectClass=user)(!(company=))) search filter is invalid.
Run Code Online (Sandbox Code Playgroud)

这是我的示例代码:

using System;
using System.DirectoryServices.AccountManagement;
using System.Security.Permissions;
using System.Linq;

namespace AdamDump
{
    class Program
    {
        static void Main(string[] args)
        {
            PrincipalContext context = new PrincipalContext(ContextType.ApplicationDirectory, "MyAdamInstance:50000", "OU=Adam Users,dc=apps01,dc=mydomain", "queryaccount", "password");        

            // initialize a Query By Example
            using (MyUserPrincipal myUserPrincipal = new MyUserPrincipal(context))
            {
                myUserPrincipal.MyAdvancedFilters.WhereCompanyNotSet();

                PrincipalSearchResult<Principal> principals = null;

                // do the search...
                using (PrincipalSearcher …
Run Code Online (Sandbox Code Playgroud)

.net c# adam active-directory account-management

9
推荐指数
1
解决办法
6104
查看次数

通过关联表的实体框架1to1关系在EDMX中不起作用

我在SQL Server数据库中有以下表 在此输入图像描述

其中有一个1-1关联表(FooBar),它在相应的FooId,BarId上有唯一索引,主键是(FooId,BarId).

要清楚的是,FooBar不允许任何FooId(由于唯一约束)不止一次出现在表中,任何BarId(由于唯一约束)都不会在表中多次出现.这就是使其成为1-1关联表的原因.

我希望在Foo和Bar之间建立这种关联表而不是1-1关系,因为在我的真实世界场景中,Bar将与其他不相关的表有其他关系,我将需要类似的关联表(而不是向Bar添加新的FK列)对于每个新表)

然后我将这些表格带入我的EDMX设计师.这种关系是以多对多而非一对一的方式引入的. 在此输入图像描述

这当然不是我想要的.我可以手动将模型更改为1-1关系. 在此输入图像描述

但后来我得到了一个错误(在设计师中). 在此输入图像描述

这是一个错误还是不可能在EF中以这种方式创建1-1关联?

c# sql-server entity-framework edmx entity-framework-6

9
推荐指数
1
解决办法
1432
查看次数

如何在带有绑定的TextBlock中实现NullText?

我想为绑定到ViewModel中的属性的TextBlock实现"NullText"行为.当ViewModel中的该属性为null或为空时,我想显示类似" 无数据 "的灰色斜体文本.我希望这遵循MVVM模式,但我迷路了......

更新 所以在使用James Webster建议的解决方案之后,我让它像这样工作......

<UserControl.Resources>
    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
    <c:NullOrEmptyValueConverter x:Key="NullOrEmptyValueConverter" Text="(No Data)"/>
</UserControl.Resources>

 ...     

<TextBlock Name="SerialNumberTextBlock" Text="{Binding Path=SerialNumber, Converter={StaticResource NullOrEmptyValueConverter}}">
    <TextBlock.Resources>
        <Style TargetType="TextBlock">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=SerialNumberTextBlock, Path=Text}" Value="(No Data)">
                    <Setter Property="FontStyle" Value="Italic"/>
               </DataTrigger>
           </Style.Triggers>
        </Style>
    </TextBlock.Resources>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

c# wpf

8
推荐指数
1
解决办法
2822
查看次数

使用WCF ServiceDiscoveryBehavior公告端点时,"定期重新发布"服务?

我有一个托管有已知URI的托管发现服务.我有一个可发现的服务,当它启动时,它使用添加到服务的ServiceDiscoveryBehavior的AnnouncementEndpoint宣布自己.

我想解决的具体用例如下:

  1. 托管发现服务启动.
  2. 可发现的服务启动并向Managed Discovery服务宣布自己.
  3. 重新启动Managed Discovery服务(出于各种可能的原因).

那么可发现的服务如何刷新自己(重新宣布)到托管发现服务?

我知道托管发现服务可以保留端点并在启动时恢复它们,但我希望所有内容都是动态的并且自我修复,这样就不会有过时的端点信息.

另一种用例是:

  1. 现有的可发现服务正在运行.
  2. 新的托管发现服务将联机.

我们如何强制或调用相同的公告服务合同调用新的托管发现服务?

我希望这是关于我想要完成的事情的足够信息.

wcf .net-4.0 service-discovery discovery

8
推荐指数
1
解决办法
1629
查看次数

如何使用Model First方法使用动态连接字符串,但仍然使用EDMX中的数据模型?

我使用EF 5和Model First方法创建了一个EDMX,即我从一个空白设计师开始并模拟我的实体.现在,我希望能够使用EDMX中定义的此模型,但提供运行时SQL Server连接字符串,而无需修改配置文件.

我知道如何将连接字符串传递给DbContext,但问题是找到程序集中映射的元数据.

例如,我的EDMX在app.config中有这个连接字符串

<add name="MesSystemEntities" connectionString="metadata=res://*/Data.DataContext.EntityFramework.MesSystem.csdl|res://*/Data.DataContext.EntityFramework.MesSystem.ssdl|res://*/Data.DataContext.EntityFramework.MesSystem.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MyMachine;initial catalog=MesSystem;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
Run Code Online (Sandbox Code Playgroud)

我失踪的部分是 "metadata=res://*/Data.DataContext.EntityFramework.MesSystem.csdl|res://*/Data.DataContext.EntityFramework.MesSystem.ssdl|res://*/Data.DataContext.EntityFramework.MesSystem.msl;"

我希望能够以DbContext编程方式创建一个SQL Server连接字符串,但"添加"元数据部分.

这就是我希望T4文件生成的内容......

public partial class MesSystemEntities : DbContext
{
    public MesSystemEntities()
        : base("name=MesSystemEntities")
    {
    }

    public MesSystemEntities(string sqlServerConnectionString)
        : base(GetEfConnectionString(sqlServerConnectionString))
    {    
    }

    private string GetEfConnectionString(string sqlServerConnectionString)
    {
       // values added by T4 generation
       string format = "metadata=res://*/Data.DataContext.EntityFramework.MesSystem.csdl|res://*/Data.DataContext.EntityFramework.MesSystem.ssdl|res://*/Data.DataContext.EntityFramework.MesSystem.msl;;provider=System.Data.SqlClient;provider connection string=\"{0}\"";    
       return String.Format(format, sqlServerConnectionString);
    }
...
}
Run Code Online (Sandbox Code Playgroud)

我的问题是如何在T4生成文件中获取我需要的元数据来创建实体框架连接,而无需为每个EDMX文件对其进行硬编码

要么

是否有更简单的方法以编程方式从程序集加载元数据?

c# t4 entity-framework .net-4.5 entity-framework-5

8
推荐指数
1
解决办法
4704
查看次数

如何保持DataGridRow焦点和选择同步?

我有一个,DataGrid并且我希望所选行和关注行进行同步,即,如果关注行发生变化,那么所选行也会发生变化,并且如果所选行发生变化,它将成为关注行。

给定带有以下XAML的WPF窗口,我如何同步已聚焦的行和选定的行?

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Grid>
        <Grid.Resources>

            <x:Array x:Key="MyList" Type="sys:String" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib">
                <sys:String>Hello</sys:String>
                <sys:String>World</sys:String>
                <sys:String>World</sys:String>
                <sys:String>World</sys:String>
                <sys:String>World</sys:String>
                <sys:String>World</sys:String>
                <sys:String>World</sys:String>
                <sys:String>World</sys:String>
                <sys:String>World</sys:String>
            </x:Array>

            <Style TargetType="{x:Type DataGrid}">
                <Setter Property="AlternationCount" Value="2" />
                <Setter Property="AutoGenerateColumns" Value="False"/>
            </Style>

            <Style TargetType="{x:Type DataGridCell}">
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="Focusable" Value="False"/>
            </Style>

            <Style TargetType="{x:Type DataGridRow}">
                <Setter Property="Focusable" Value="True"/>
                <Style.Triggers>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="AlternationIndex" Value="0"/>
                            <Condition Property="IsSelected" Value="False"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="Background" Value="White"/>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="AlternationIndex" Value="1"/>
                            <Condition Property="IsSelected" Value="False"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="Background" …
Run Code Online (Sandbox Code Playgroud)

.net wpf xaml wpfdatagrid c#-4.0

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