小编Tea*_*Dev的帖子

从 F# 访问显式转换运算符

使用 npgsql 从 postgresql 读取日期值时出现以下错误:

This expression was expected to have type
    DateTime    
but here has type
    NpgsqlTypes.NpgsqlDate  
Run Code Online (Sandbox Code Playgroud)

现在 npgsql 文档引用了正在定义的显式运算符:

[C#]
public static explicit operator DateTime(
    NpgsqlDate date
);
Run Code Online (Sandbox Code Playgroud)

但我不知道如何从 F# 访问它。

有几种笨拙的、简单的方法可以实现我所需要的,但我感到失望和沮丧,因为我无法找到访问内置演员的方法。

我尝试了旧的 Convert.ToDateTime(...),但即使这样也不起作用。

有人有线索吗?谢谢。

f# npgsql

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

Autofac:解析同名的IEnumerable注册

我正在使用Autofac来处理我的应用程序中的依赖注入.为了不必明确地进行每一次注册,我首先使用RegisterAssemblyTypes().AsImplementedInterfaces()然后只处理那些需要特殊配置的注册.

我有一个名为的接口IToolStripPopulator有几个不同的实现,其中一些正在使用,但有些不再使用(因为我正在努力工作并遵守OCP,如果我需要不同的功能,我通常不会更改它们,而是让他们独自一人,创造新的,做我现在需要的东西).出于这个原因,我需要以两种方式覆盖接口的自动注册:

  • 一个实现是注入我的主逻辑,并作为其他几个的装饰器.我自然希望通过As<IToolStripPopulator>()它来注册并完成它,因为这是我的应用程序的功能目前依赖的实现.
  • 那些其他实现是仅在该装饰器类中使用的"内部"填充器.注入它们有两种方法:
    • 使用特定类型明确地将外部实现的构造函数连接起来; 这是不是很漂亮,还因为该构造函数将不得不采取内部populators的确切数目我使用的,现在,这是不兼容OCP.
    • 外部实现需要IEnumerable<IToolStripPopulator>; 这就是我想做的事情,但它也是我被困的地方.

我不能让Autofac自行解决这个IEnumerable问题,因为它只会解析接口的所有实现,甚至那些我不再使用的实现以及我不想要的"外部"(以及在解决期间可能会导致无限循环).

所以我想做的是:

// the inner populators
builder.RegisterType<BrowsersMenuPopulator>().Named<IToolStripPopulator>("inner");
builder.RegisterType<ThreadsafeConnectionMenuPopulator>().Named<IToolStripPopulator>("inner");

// the decorator implementation
builder.RegisterType<BrowserAndConnectionMenuPopulator>().As<IToolStripPopulator>().WithParameter( ? );
Run Code Online (Sandbox Code Playgroud)

但是,此时无法实际访问现有注册.

c# dependency-injection ioc-container inversion-of-control autofac

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

Rx 2.1:如何在Dispatcher上正确订阅和观察

首先,我使用最新的Rx,即2.1.据我所知,当Rx变为2时,很多事情都发生了变化,所以我真的很期待收到最新的答案.提前致谢.

我正在为Rx实现一个经典任务:观察TextBox的文本(确切地说是来自WPToolkit的AutoCompleteBox),以便向用户提供建议列表.建议来自网络,我想使用这些普通的Rx好东西,如Throttle,DistinctUntilChanged等.

我也在使用最近发布的适用于Windows Phone 8的便携式HttpClient,因为它提供了基于任务的异步API,这很不错.

我遇到的问题是在读取Text 'AutoCompleteBox` 的值时的跨线程访问.这是代码:

var http = new HttpClient();
var searchFunc = Observable.FromAsync<HttpResponseMessage>(() => 
            http.GetAsync(FormatUrl(SEARCH_URL, "DE", new GeoCoordinate(51, 13), searchBox.Text /* <-- causes exception */, 10, "")));

var uithread = new SynchronizationContextScheduler(SynchronizationContext.Current);
var textChange = Observable.FromEventPattern<RoutedEventArgs>(searchBox, "TextChanged")                             
        .Throttle(TimeSpan.FromMilliseconds(800))
        .DistinctUntilChanged()     
        .SubscribeOn(uithread)           
        .SelectMany(searchFunc)                
        .Select(async (resp) => SearchResultsParser.ParseSearchResults(await resp.Content.ReadAsStreamAsync(), new GeoCoordinate(51, 13)))
        .Select(async (results) => searchBox.ItemsSource = await results)
        .ObserveOn(uithread)
        .Subscribe();
Run Code Online (Sandbox Code Playgroud)

searchFunc执行时会发生异常.我从VS看到它在Worker Thread上执行,尽管我使用了SubscribeOn.

这是使用的示例SynchronizationContextScheduler,但我也尝试过SubscribeOnDispatcher,结果相同.看起来我错过了一些重要的ObserveOn东西,或者可能是关于Observable.FromAsync.你能不能指出我的错误?

system.reactive observable windows-phone-8

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

通过反射在同一个程序集上生成代码

我已经开始涉足T4并且第一次相处得很好,但后来遇到了一个实际上非常明显并且可能无法解决的问题,但也许有一种方法我只是缺乏了解或看到的经验.

鉴于以下课程:

public class T4Test : CodeActivity
{
    protected override void Execute(CodeActivityContext context)
    {
    }

    [Input("InX")]
    public InArgument<string> InX { get; set; }

    [Output("OutX")]
    public OutArgument<string> OutX { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我希望这作为输出:

public class ActivityWrapper
{
    private readonly T4Test _activity;
    private readonly ActivityContext _context;

    public ActivityWrapper(T4Test activity, ActivityContext context)
    {
        this._activity = activity;
        this._context = context;
    }

    public string InX
    {
        get { return this._activity.InX.Get(this._context); }
    }

    public string OutX
    {
        get { return this._activity.OutX.Get(this._context); }
        set { this._activity.OutX.Set(this._context, …
Run Code Online (Sandbox Code Playgroud)

.net c# reflection t4

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

Autofac:解析对命名实例的特定依赖关系

使用Autofac,我想注册一个组件并指定要解析为命名实例的特定依赖项.

我使用构造函数注入找到了类似下面的示例,这几乎是我想要的.

builder.Register(c => new ObjectContainer(ConnectionStrings.CustomerDB))
    .As<IObjectContainer>()
    .Named("CustomerObjectContainer");

builder.Register(c => new ObjectContainer(ConnectionStrings.FooDB))
    .As<IObjectContainer>()
    .Named("FooObjectContainer");

builder.Register(c => new CustomerRepository(
    c.Resolve<IObjectContainer>("CustomerObjectContainer"));

builder.Register(c => new FooRepository(
    c.Resolve<IObjectContainer>("FooObjectContainer"));
Run Code Online (Sandbox Code Playgroud)

但是,我需要使用属性注入,我不想指定所有依赖项.

就像是:

builder.Register<CustomerRepository>().With<IObjectContainer>("CustomerObjectContainer");    
builder.Register<FooRepository>().With<IObjectContainer>("FooObjectContainer");
Run Code Online (Sandbox Code Playgroud)

所有未指定的依赖项的构建应该在未命名的实例中发生.

谢谢,亚历克斯

[丹尼尔克回答]

对于该类型的任何属性,按类型解析的重载.

    public static IRegistrationBuilder<TLimit, TReflectionActivatorData, TStyle> WithDependency<TLimit, TReflectionActivatorData, TStyle, TProperty>(
        this IRegistrationBuilder<TLimit, TReflectionActivatorData, TStyle> registration,
        Func<IComponentContext, TProperty> valueProvider)
        where TReflectionActivatorData : ReflectionActivatorData
    {
        return registration.WithProperty(new ResolvedParameter((p, c) =>
            {
                PropertyInfo prop;
                return p.TryGetDeclaringProperty(out prop) &&
                    prop.PropertyType == typeof(TProperty);
            },
            (p, c) => valueProvider(c)));
    }
Run Code Online (Sandbox Code Playgroud)

ioc-container autofac

3
推荐指数
1
解决办法
6823
查看次数

使用Nancy.Testing.Browser发布时出现ConfigurableBootstrapper错误

我有一个简单的NancyModule,它有一个Post声明:

Post["/Car/New"] = args => 
{
    Car newCar = this.Bind<Car>();
    newCar = _carRepos.CreateNewCar(newCar);
    return Response.AsJson<Car>(newCar);
};
Run Code Online (Sandbox Code Playgroud)

从视图发布到这个工作正常:

<form action="/Car/New" method="post">
    <input type="text" name="colour" />
    <input type="submit" value="Submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

当我尝试为此路由运行测试时,出现以下错误:

System.Exception : ConfigurableBootstrapper Exception
  ----> Nancy.RequestExecutionException : Oh noes!
  ----> System.MissingMethodException : Method not found: '!!0 Nancy.ModelBinding.ModuleExtensions.Bind(Nancy.INancyModule, System.String[])'.
Result StackTrace:  
at Nancy.Testing.PassThroughStatusCodeHandler.Handle(HttpStatusCode statusCode, NancyContext context)
at Nancy.NancyEngine.CheckStatusCodeHandler(NancyContext context)
at Nancy.NancyEngine.HandleRequest(Request request, Func`2 preRequest)
at Nancy.NancyEngine.HandleRequest(Request request)
at Nancy.Testing.Browser.HandleRequest(String method, String path, Action`1 browserContext)
at Nancy.Testing.Browser.Post(String path, Action`1 browserContext)
at Shopr.Tests.Cars.CarTests.PostNewCarReturnsCar() …
Run Code Online (Sandbox Code Playgroud)

unit-testing nancy

3
推荐指数
1
解决办法
2283
查看次数

避免使用Option.Value

我有这样的类型:

type TaskRow =
    {
        RowIndex : int
        TaskId : string
        Task : Task option
    }
Run Code Online (Sandbox Code Playgroud)

函数将返回这些记录的列表,以供进一步处理。有些这样做处理功能仅适用于有关TaskRow地方的项目TaskSome。我想知道最好的方法是什么。

天真的方法会这样做

let taskRowsWithTasks = taskRows |> Seq.filter (fun row -> Option.isSome row.Task)
Run Code Online (Sandbox Code Playgroud)

并将其传递给那些函数,只需假设Task它将永不存在,None并使用Task.Value,如果我不传递该特殊列表,就会冒NRE的风险。这正是当前的C#代码所做的,但是对于F#来说似乎很简单。我不应该“假设”事情,而应该让编译器告诉我什么将起作用。

更具“功能性”的是每次值相关时都进行模式匹配,然后对进行任何操作/不返回任何值(或使用choose类似方法)None,但这似乎是重复的和浪费的,因为同一工作将被重复执行多次。

另一个想法是引入第二种稍有不同的类型:

type TaskRowWithTask =
    {
        RowIndex : int
        TaskId : string
        Task : Task
    }
Run Code Online (Sandbox Code Playgroud)

然后,原始列表将被过滤到这种“子列表”中,以便在适当的情况下使用。从功能的角度来看,我认为这是可以的,但是我想知道是否有一种更好的,惯用的方式而不求助于这种“帮助类型”。

感谢您的指导!

f# idiomatic

3
推荐指数
1
解决办法
139
查看次数

F#Rx扩展具有并发事件的IObservable

我有以下使用FSharp.Reactive的F#代码.函数reactToEvents接受两个事件源并生成一个应用程序状态源.然后UI使用应用程序状态

open FSharp.Reactive

let reactToEvents (initialSettings:Settings) 
            (incomingTweets: ITweet IObservable) 
            (uiActions: UserInput IObservable) :  State IObservable = 
    let initialState = { settings = initialSettings; tweets = [] }

    let tweetInput = Observable.map TweetReceived incomingTweets 
    let userInput = Observable.map UserAction uiActions
    let allInput = Observable.merge userInput tweetInput

    Observable.scan transition initialState allInput
Run Code Online (Sandbox Code Playgroud)

在上面的函数中,在UI线程上生成uiActions时,在一个线程上生成incomingTweets事件.

像我上面那样使用Observable.merge合并两个源是否安全?

使用上面的Observable.scan扫描生成的源是否安全?

如果这不正确,那么正确的方法是什么?

谢谢!

更新1:

我希望至少Observable.merge不关心线程.我发现了这个,似乎说它们使用起来并不安全:

http://msdn.microsoft.com/en-us/library/ee353488.aspx

http://msdn.microsoft.com/en-us/library/ee353749.aspx

"对于每个观察者来说,注册的中间观察对象不是线程安全的.也就是说,源不会在不同的线程上同时触发源的观察."

那么正确的方法是什么呢?

更新2:

这是一个混乱.我链接的文档是用于从名称空间Microsoft.FSharp.Control.Observable合并和扫描的函数.这与我在我的代码中使用的Rx不同.对于真正的Rx,您需要使用库FSharp.Reactive和FSharp.Reactive.Observable下的函数.

f# multithreading reactive-programming system.reactive

2
推荐指数
1
解决办法
404
查看次数

显然F#/ BCL浮点错误

以下是FSI:

> System.Math.Round(0.2916, 2);;
val it : float = 0.29
> it * 100.;;
val it : float = 29.0
> int it;;
val it : int = 28
Run Code Online (Sandbox Code Playgroud)

结果与我尝试的任何地方相同 - 编译的F#3.1/.NET 4.0应用程序,Visual Studio 2013和2015中的FSI,.NET Fiddle,@ fsibot ....

当然这是某个地方的错误,不是吗?这里发生了什么?

.net f# base-class-library

2
推荐指数
3
解决办法
124
查看次数

用c#中的notepad ++打开文件进行读取

我试着用c#语言用notepad ++打开文件进行阅读.我用这个命令:

Process myProcess = new Process();
Process.Start("notepad++.exe", @"c:\file name for test.txt");
Run Code Online (Sandbox Code Playgroud)

notepad ++无法使用全名打开此文件,

notepad ++将名称剪切为4部分,并返回此消息

c:\ file不存在.创建它?

c:\name不存在.创建它?

c:\ for不存在.创建它?

c:\ test.txt不存在.创建它?

版本的记事本++:9.4.2

在较新的版本中我没有这个问题,但我需要在所有版本中使用notepad ++.

c#

2
推荐指数
1
解决办法
4574
查看次数