I have below code in C#. And It is working Good.
WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
WindowsImpersonationContext ctx = winId.Impersonate();
ctx.Undo();
But i am tring to convert this code in F#. I have written below code.
Let winId = HttpContext.Current.User.Identity :> WindowsIdentity //Showing error
Let ctx = winId.Impersonate()
ctx.Undo()
In above code HttpContext.Current.User.Identity is not able cast in WindowsIdentity. Please let me know how can I do this.
The problem is that you're using the upcasting (:>) operator when you want to use the downcasting (:?>) operator. Upcasting is checked at compile time since you can always know if you can cast up the inheritance hierarchy, but casting down the hierarchy can fail, so it has a separate operator which can fail at runtime.
Related
I want to create a flow that creates a new source (it will be a persistence query) out of incoming elements, and then flattens the results. Something like this simplified example:
var z = Source.Single(1).ConcatMany(i => Source.Single(i));
this code compiles and works as expected. My problem is that when I translate it to F#:
let z = Source.Single(1).ConcatMany(fun i -> Source.Single(i))
I get an error saying
This expression was expected to have type
'IGraph<SourceShape<'a>,Akka.NotUsed>'
but here has type
'Source<int,Akka.NotUsed>'
I think that the cause of that is that F# handles co/contravariance differently than C# and cannot simply convert these generic specializations (https://github.com/fsharp/fslang-suggestions/issues/162), but I cannot figure out a way to make a convertion between an int and a SourceShape<int>. Is it possible to convert this example to F#?
Looking at the code on GitHub, it appears that Source<TOut, TMat> is a direct implementation of IGraph, so you should just be able to cast it:
public sealed class Source<TOut, TMat> : IFlow<TOut, TMat>, IGraph<SourceShape<TOut>, TMat>
let z = Source.Single(1).ConcatMany(fun i -> Source.Single(i) :> IGraph<SourceShape<int>,Akka.NotUsed>)
I think the biggest difference between the C# and F# usage is that C# will automatically do the upcast for you.
One workaround that I found is to use Akkling.Streams wrapper library:
open Akkling.Streams
let x =
Source.singleton 1
|> Source.collectMap(fun x -> Source.singleton x)
the question how to do this without Akkling remains open.
I am trying to add a F#-style interface to a type, that has a byref return method.
Here's the code:
type IPool<'P, 'T when 'T: struct> =
abstract member GetReference: ITypedPointer<'P, 'T> -> byref<'T>
let Ref<'TPool, 'P, 'T when 'TPool :> IPool<'P, 'T>> (pool: 'TPool) pointer =
pool.GetReference pointer
Now to my surprise, a similar thing worked fine until I introduced IPool interface. Before that Ref itself contained an implementation like &pool.data.[idx], and worked fine.
I tried installing nightly build of F# Tools, cause latest release does not officially support byref returns, and PR to introduce them was recently completed: https://github.com/Microsoft/visualfsharp/pull/4888
However, I still get error FS3209: The address of the variable 'copyOfStruct' cannot be used at this point. A method or function may not return the address of this local value. in Visual Studio. Type outref<T> still does not seem to be available either. Am I missing something?
I also tried to drop the pointer parameter, and just return pool.GetReference to only get a different error message.
Addition: the ultimate goal is to be able to do
let aref = Ref pool ptr
let bref = Ref pool ptr
aref <- 42
assert(aref = bref)
e.g. give caller a direct reference to an internal memory, usually backed by an array, similar to Span<T>. I am making this for performance reasons, so it is not OK to allocate on every call to Ref.
For some reason, reducing generalization helped to get rid of the error:
let Ref<'P, 'T when 'T: struct> (pool: IPool<'P, 'T>) pointer = pool.GetReference pointer
Solution provided by
https://github.com/Microsoft/visualfsharp/issues/5366#issuecomment-407521220
Though it does not explain why the original code does not compile.
I don't think it's standard practice to return a byref type. This type is really meant for method parameters, mostly for C# interop with out or ref parameters. Take a look at this StackOverflow question for a good explanation.
What you can do is change the method on your interface to take a tuple of ITypedPointer<'P,'T> and byref<'T> (usage of byref is not allowed with curried parameters) and return unit instead. Then you can call GetReference like any standard .NET method with an out parameter in C#. That would look something like this:
type ITypedPointer<'P, 'T> = interface end
type IPool<'P, 'T when 'T: struct> =
abstract member GetReference: ITypedPointer<'P, 'T> * byref<'T> -> unit
let Ref<'TPool, 'P, 'T when 'TPool :> IPool<'P, 'T>> (pool: 'TPool) pointer =
let mutable value = Unchecked.defaultof<'T>
pool.GetReference(pointer, &value)
value
I can't get this piece of code to pass.
[<Test>]
member public this.Test() =
let mock = new Mock<IList<string>>()
let mockObj = mock.Object
mockObj.Add("aaa")
mock.Verify(fun m -> m.Add(It.IsAny<string>()), Times.Once())
Exception I get:
System.ArgumentException : Expression of type 'System.Void' cannot be used for constructor parameter of type 'Microsoft.FSharp.Core.Unit'
I believe it has something to do with F# not inferring properly the data type of labda expression but I don't know how to fix that.
You are correct, this an issue with F# type inference when calling an overloaded method that accepts either Action or Func.
One option is to download the Moq.FSharp.Extensions from Nuget and change your Verify to an explicit VerifyAction, i.e.
open Moq.FSharp.Extensions
type MyTests() =
[<Test>]
member public this.Test() =
let mock = new Mock<IList<string>>()
let mockObj = mock.Object
mockObj.Add("aaa")
mock.VerifyAction((fun m -> m.Add(any())), Times.Once())
Underneath the covers the Moq.FSharp.Extensions simply defines an extension method VerifyAction that only takes an Action to avoid ambiguity:
type Moq.Mock<'TAbstract> when 'TAbstract : not struct with
member mock.VerifyAction(expression:Expression<Action<'TAbstract>>) =
mock.Verify(expression)
Another option is to use Foq, a mocking library with a similar API to Moq but designed specifically for use from F#, also available via Nuget:
[<Test>]
member public this.Test() =
let mock = Mock.Of<IList<string>>()
mock.Add("aaa")
Mock.Verify(<# mock.Add(any()) #>, once)
I'm a hobbyist programmer (cook by trade) that's currently trying to teach myself F# and functional programming in general.
Anyway, I was fooling around with DeflateStream and wrote the following two functions:
let Compress compressMe =
let ds = new DeflateStream(File.Create("compressed.txt"), CompressionMode.Compress)
File.OpenRead(compressMe).CopyTo(ds)
ds.Close()
let Decompress =
let ds = new DeflateStream(File.OpenRead("compressed.txt"), CompressionMode.Decompress)
ds.CopyTo(File.Create("decompressed.txt"))
ds.Close()
In the body of the main function they are called one right after the other like this:
Compress args.[0]
Decompress
However, if compressed.txt doesn't exist when the program is run Decompress throws a FileNotFoundException which is surprising because the only thing that could throw this is the call to File.OpenRead("compress.txt"). After about an hour I figured out that Decompress was implementing IComparable and was being executed before the call to it in the main function. I found that by changing its definition to let Decompress () = [...] it no longer implemented IComparable and my code executed as it was intended to. Can anyone tell me why F# was infering IComparable and why such and inference would cause the function to execute before the main function marked with [<EntryPoint>]? Also, please forgive the imperitive style of my code, I'm incredibly new at this.
Thanks in adavance.
I'm not entirely sure about the IComparable bit, but the issue you have is that without the parentheses, the compiler is treating Decompress as a value not a function. This would be similar to if you had written.
let compressedName = "compressed.txt"
in that case, compressedName is now a value. Adding the parentheses tells the compiler that this is a function whose code must be called each time the function is rather than a value initialized once (before the entry point) by the code you wrote.
When you write something like
let value =
//some long calculation
[<Entrypoint>]
let main args = ...
The compiler executes the long calculation before main. This is because you probably use the value later in your code. To suppress this, as you found, you need to use let value() = ....
I am not sure where Icomparable is coming from, but this is the key to what is happening.
Note, if you write
let a = ...
let b = ...
The compiler will gurantee a is calculated before b executes.
As others have pointed out, the absence of parentheses in the declaration is significant.
let Decompres = ...
declares a variable of type unit. This type is used to represent "data" (even if this data doesn't encode much information), and it implements IComparable like any other data-oriented type.
let Decompress() = ...
declares a function, and functions in F# are not comparable, probably because there is no universally accepted notion of equality on functions.
I can't see that the "IComparable-ness" of Decompress had anything to do with the exception you got.
I am playing with type providers and I am trying to compile a quotation into a public static method of a new generated type. Here is what I have:
let CreateType<'i> name methodName quotation =
let assemblyName = new AssemblyName(Name = "tmpAssembly")
let assemblyBuilder =
System.AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave)
let filename = "tmpAssembly.dll"
let tmpModule = assemblyBuilder.DefineDynamicModule(filename,filename)
// create a new type builder
let typeBuilder =
tmpModule.DefineType(
name,
TypeAttributes.Public ||| TypeAttributes.Class,
null, // parentType
[|typeof<'i>|])
let attr = MethodAttributes.Public ||| MethodAttributes.HideBySig ||| MethodAttributes.Static
let methodImpl =
typeBuilder.DefineMethod(
methodName,
attr,
typeof<unit>, // todo
[||]) // todo
let il = methodImpl.GetILGenerator()
// compile quotation to method
typeBuilder.CreateType()
I know there is a .Compile() method but I think that's not what I need. Any ideas?
I haven't really played with the F# 3.0 release yet, but I think that you don't need to generate IL code yourself. The post by Keith explains that there are two types of type providers - generated that create a real .NET type (that exists in some library) and erased that create a fake type and then give the compiler an expression tree to be used in place of the calls to the fake type.
It seems to me that you're trying to implement generated type provider in a situation where erased type would be more appropriate. In the erased case, you should be just able to return the .NET Expression<..> type (not the F# quotation though, but you can use ToLinqExpression from PowerPack) and the F# compiler will compile that for you.
However, I haven't played with it yet, so I don't know what's the exact mechanism.