Coder Social home page Coder Social logo

cs2fs's Introduction

Jindřich (Jindra) Ivánek

F# developer

Blog: https://jindraivanek.hashnode.dev

Projects: https://jindraivanek.hashnode.dev/projects

Brief F# OSS history

  • 2012 - started using F#
  • 2014 - started using F# professionally - Shift planning optimization at AristoTelos
  • 2017 - first Fantomas PR
  • 2018 - Started co-operating with Florian (@nojaf) on Fantomas
  • 2018 - Fantomas Online released - base of Fantomas Tools
  • 2019 - Fantomas 3 released
  • 2020 - child born - OSS parent break :)
  • 2023 - joined F# team at Ciklum Western Europe (former CN Group)



Mark streak

cs2fs's People

Contributors

codernate avatar jindraivanek avatar matthid avatar vilinski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cs2fs's Issues

Converting small function throws exception

This conversion threw an error (System.ArgumentException: The option value was None (Parameter 'option'))
public static int ToInt32(string value)
{
int.TryParse(value, out int result);
return result;
}

Missing license

It's a really interesting project. Could you provide a license file (it's also recommended to add a license description - a note referencing the license text file - to each source code file) to the project?

Support C# => anonymous functions

I have noted that if i remove anonymous functions and replace them with regular functions, the conversion succeds, but it fails if lambda functions (or anonymous functions) are present, does not fail with properties, but just with functions with at least 1 argument, for example

        public string Hello(string test) => "HI";

this will fail with object reference not set

'The option value was None' error when converting struct

Converting the following throws an error in exprF because of the expression getParentOfType<Syntax.ClassDeclarationSyntax> n |> Option.get

struct X
{
    void SomeFunc(int arg)
    {
        var x = arg;
    }
}

The fix is to just to change ClassDeclarationSyntax to TypeDeclarationSyntax so that it works with structs.

Early return could be doable with if-else?

Documentation says early returns are not supported.
What this means?

I think early return could be doable:

if(x){
    /* some return */
    return f;
}
var c = 3;
// ...

with:

if x then
    (* some return *)
    f
else
let c = 3
// ...

Constructor can be simplified

image

This one doesnt seem correct in F#..

the argument should be passed as parameter if it's a private readonly field,
and could be then directly assigned without mutation , and no need of extra New(..) ?

type Animal(name: string) = 
      //name can be used here and assigned to properties..
      member val Name = name with get

no readme :(

Can you provide a readme stating how to build and use this experimental repo 😛 ?
I want to try it out! 😄

Object reference not set to an instance of an object

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------



[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.2")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://ec.gob.sri.ws.recepcion", ConfigurationName="RecepcionComprobantesOffline")]
public interface RecepcionComprobantesOffline
{
    
    [System.ServiceModel.OperationContractAttribute(Action="", ReplyAction="*")]
    [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
    [System.ServiceModel.ServiceKnownTypeAttribute(typeof(mensaje[]))]
    [System.ServiceModel.ServiceKnownTypeAttribute(typeof(comprobante[]))]
    System.Threading.Tasks.Task<validarComprobanteResponse> validarComprobanteAsync(validarComprobante request);
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.2")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://ec.gob.sri.ws.recepcion")]
public partial class respuestaSolicitud
{
    
    private string estadoField;
    
    private comprobante[] comprobantesField;
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=0)]
    public string estado
    {
        get
        {
            return this.estadoField;
        }
        set
        {
            this.estadoField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)]
    [System.Xml.Serialization.XmlArrayItemAttribute(IsNullable=false)]
    public comprobante[] comprobantes
    {
        get
        {
            return this.comprobantesField;
        }
        set
        {
            this.comprobantesField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.2")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://ec.gob.sri.ws.recepcion")]
public partial class comprobante
{
    
    private string claveAccesoField;
    
    private mensaje[] mensajesField;
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=0)]
    public string claveAcceso
    {
        get
        {
            return this.claveAccesoField;
        }
        set
        {
            this.claveAccesoField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)]
    [System.Xml.Serialization.XmlArrayItemAttribute(IsNullable=false)]
    public mensaje[] mensajes
    {
        get
        {
            return this.mensajesField;
        }
        set
        {
            this.mensajesField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.2")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://ec.gob.sri.ws.recepcion")]
public partial class mensaje
{
    
    private string identificadorField;
    
    private string mensaje1Field;
    
    private string informacionAdicionalField;
    
    private string tipoField;
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=0)]
    public string identificador
    {
        get
        {
            return this.identificadorField;
        }
        set
        {
            this.identificadorField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("mensaje", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)]
    public string mensaje1
    {
        get
        {
            return this.mensaje1Field;
        }
        set
        {
            this.mensaje1Field = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=2)]
    public string informacionAdicional
    {
        get
        {
            return this.informacionAdicionalField;
        }
        set
        {
            this.informacionAdicionalField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=3)]
    public string tipo
    {
        get
        {
            return this.tipoField;
        }
        set
        {
            this.tipoField = value;
        }
    }
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.2")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="validarComprobante", WrapperNamespace="http://ec.gob.sri.ws.recepcion", IsWrapped=true)]
public partial class validarComprobante
{
    
    [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://ec.gob.sri.ws.recepcion", Order=0)]
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, DataType="base64Binary")]
    public byte[] xml;
    
    public validarComprobante()
    {
    }
    
    public validarComprobante(byte[] xml)
    {
        this.xml = xml;
    }
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.2")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="validarComprobanteResponse", WrapperNamespace="http://ec.gob.sri.ws.recepcion", IsWrapped=true)]
public partial class validarComprobanteResponse
{
    
    [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://ec.gob.sri.ws.recepcion", Order=0)]
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public respuestaSolicitud RespuestaRecepcionComprobante;
    
    public validarComprobanteResponse()
    {
    }
    
    public validarComprobanteResponse(respuestaSolicitud RespuestaRecepcionComprobante)
    {
        this.RespuestaRecepcionComprobante = RespuestaRecepcionComprobante;
    }
}

[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.2")]
public interface RecepcionComprobantesOfflineChannel : RecepcionComprobantesOffline, System.ServiceModel.IClientChannel
{
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.2")]
public partial class RecepcionComprobantesOfflineClient : System.ServiceModel.ClientBase<RecepcionComprobantesOffline>, RecepcionComprobantesOffline
{
    
    /// <summary>
    /// Implement this partial method to configure the service endpoint.
    /// </summary>
    /// <param name="serviceEndpoint">The endpoint to configure</param>
    /// <param name="clientCredentials">The client credentials</param>
    static partial void ConfigureEndpoint(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Description.ClientCredentials clientCredentials);
    
    public RecepcionComprobantesOfflineClient() : 
            base(RecepcionComprobantesOfflineClient.GetDefaultBinding(), RecepcionComprobantesOfflineClient.GetDefaultEndpointAddress())
    {
        this.Endpoint.Name = EndpointConfiguration.RecepcionComprobantesOfflinePort.ToString();
        ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
    }
    
    public RecepcionComprobantesOfflineClient(EndpointConfiguration endpointConfiguration) : 
            base(RecepcionComprobantesOfflineClient.GetBindingForEndpoint(endpointConfiguration), RecepcionComprobantesOfflineClient.GetEndpointAddress(endpointConfiguration))
    {
        this.Endpoint.Name = endpointConfiguration.ToString();
        ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
    }
    
    public RecepcionComprobantesOfflineClient(EndpointConfiguration endpointConfiguration, string remoteAddress) : 
            base(RecepcionComprobantesOfflineClient.GetBindingForEndpoint(endpointConfiguration), new System.ServiceModel.EndpointAddress(remoteAddress))
    {
        this.Endpoint.Name = endpointConfiguration.ToString();
        ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
    }
    
    public RecepcionComprobantesOfflineClient(EndpointConfiguration endpointConfiguration, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(RecepcionComprobantesOfflineClient.GetBindingForEndpoint(endpointConfiguration), remoteAddress)
    {
        this.Endpoint.Name = endpointConfiguration.ToString();
        ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
    }
    
    public RecepcionComprobantesOfflineClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(binding, remoteAddress)
    {
    }
    
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    System.Threading.Tasks.Task<validarComprobanteResponse> RecepcionComprobantesOffline.validarComprobanteAsync(validarComprobante request)
    {
        return base.Channel.validarComprobanteAsync(request);
    }
    
    public System.Threading.Tasks.Task<validarComprobanteResponse> validarComprobanteAsync(byte[] xml)
    {
        validarComprobante inValue = new validarComprobante();
        inValue.xml = xml;
        return ((RecepcionComprobantesOffline)(this)).validarComprobanteAsync(inValue);
    }
    
    public virtual System.Threading.Tasks.Task OpenAsync()
    {
        return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(null, null), new System.Action<System.IAsyncResult>(((System.ServiceModel.ICommunicationObject)(this)).EndOpen));
    }
    
    public virtual System.Threading.Tasks.Task CloseAsync()
    {
        return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginClose(null, null), new System.Action<System.IAsyncResult>(((System.ServiceModel.ICommunicationObject)(this)).EndClose));
    }
    
    private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration)
    {
        if ((endpointConfiguration == EndpointConfiguration.RecepcionComprobantesOfflinePort))
        {
            System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding();
            result.MaxBufferSize = int.MaxValue;
            result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
            result.MaxReceivedMessageSize = int.MaxValue;
            result.AllowCookies = true;
            result.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport;
            return result;
        }
        throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
    }
    
    private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration)
    {
        if ((endpointConfiguration == EndpointConfiguration.RecepcionComprobantesOfflinePort))
        {
            return new System.ServiceModel.EndpointAddress("https://celcer.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantesOffli" +
                    "ne");
        }
        throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
    }
    
    private static System.ServiceModel.Channels.Binding GetDefaultBinding()
    {
        return RecepcionComprobantesOfflineClient.GetBindingForEndpoint(EndpointConfiguration.RecepcionComprobantesOfflinePort);
    }
    
    private static System.ServiceModel.EndpointAddress GetDefaultEndpointAddress()
    {
        return RecepcionComprobantesOfflineClient.GetEndpointAddress(EndpointConfiguration.RecepcionComprobantesOfflinePort);
    }
    
    public enum EndpointConfiguration
    {
        
        RecepcionComprobantesOfflinePort,
    }
}

Returns this exception:

Exception: Object reference not set to an instance of an object. Stack Trace: at System.Object.GetType()
at [email protected](SyntaxNode node)
at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc2 errorPrinter, Expr1 e)
at cs2fs.FSharpOutput.getExprNP@319[a](FSharpFunc2 errorPrinter, Expr1 e)
at [email protected](Expr1 e) at Microsoft.FSharp.Collections.Internal.IEnumerator.map@74.DoMoveNext(b& curr) at Microsoft.FSharp.Collections.Internal.IEnumerator.MapEnumerator1.System-Collections-IEnumerator-MoveNext()
at Microsoft.FSharp.Collections.SeqModule.ToList[T](IEnumerable1 source) at cs2fs.FSharpOutput.delimLineText(String sep, IEnumerable1 xs)
at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc2 errorPrinter, Expr1 e)
at cs2fs.FSharpOutput.getMember@175[a](FSharpFunc2 errorPrinter, String className, Expr1 x)
at Microsoft.FSharp.Collections.Internal.IEnumerator.map@74.DoMoveNext(b& curr)
at Microsoft.FSharp.Collections.Internal.IEnumerator.MapEnumerator1.System-Collections-IEnumerator-MoveNext() at Microsoft.FSharp.Collections.SeqModule.ToList[T](IEnumerable1 source)
at cs2fs.FSharpOutput.lineblock(IEnumerable1 xs) at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc2 errorPrinter, Expr1 e) at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc2 errorPrinter, Expr1 e) at cs2fs.FSharpOutput.getExprNP@319[a](FSharpFunc2 errorPrinter, Expr1 e) at [email protected](Expr1 e)
at Microsoft.FSharp.Collections.Internal.IEnumerator.map@74.DoMoveNext(b& curr)
at Microsoft.FSharp.Collections.Internal.IEnumerator.MapEnumerator1.System-Collections-IEnumerator-MoveNext() at Microsoft.FSharp.Collections.SeqModule.ToList[T](IEnumerable1 source)
at cs2fs.FSharpOutput.delimLineText(String sep, IEnumerable1 xs) at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc2 errorPrinter, Expr1 e) at cs2fs.FSharpOutput.getExprNP@319[a](FSharpFunc2 errorPrinter, Expr1 e) at [email protected](Expr1 e)
at Microsoft.FSharp.Collections.Internal.IEnumerator.map@74.DoMoveNext(b& curr)
at Microsoft.FSharp.Collections.Internal.IEnumerator.MapEnumerator1.System-Collections-IEnumerator-MoveNext() at Microsoft.FSharp.Collections.SeqModule.ToList[T](IEnumerable1 source)
at cs2fs.FSharpOutput.delimLineText(String sep, IEnumerable1 xs) at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc2 errorPrinter, Expr1 e) at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc2 errorPrinter, Expr1 e) at cs2fs.Convert.convertText(String csharp) at Server.Result.attempt[a](FSharpFunc2 f) in /build/src/Server/Server.fs:line 24

Add support for task CE

since task CE is available already in F# preview, would be a cool feature (to turn also async/await into task { ... let! } ), just wondering if it's possible :)

Object reference not set

namespace Enosis.Voltron.WebService.Services
{
    public class GoogleDocumentsStorageServiceOptions
    {
        public string BucketName { get; set; }
    }

    public class GoogleDocumentsStorageService : IDocumentsStorageService
    {
        private StorageClient storageClient;
        private readonly GoogleDocumentsStorageServiceOptions options;

        public GoogleDocumentsStorageService(IOptions<GoogleDocumentsStorageServiceOptions> options)
        {
            this.options = options.Value;
            storageClient = StorageClient.Create();
        }
        
        public async Task<GetFileResult> GetFile(string fileName)
        {
            var stream = new MemoryStream();

            Google.Apis.Storage.v1.Data.Object metaData;

            try
            {
                await storageClient.DownloadObjectAsync(options.BucketName, fileName, stream);

                metaData = await storageClient.GetObjectAsync(options.BucketName, fileName);
            }
            catch (Google.GoogleApiException ex)
            {
                Console.WriteLine(ex);

                return new GetFileResult()
                {
                    Success = false,
                    ErrorHttpStatusCode = Convert.ToInt16(ex.HttpStatusCode),
                    ErrorMessage = ex.Message
                };
            }

            stream.Seek(0, 0);

            return new GetFileResult()
            {
                Success = true,
                FileStream = stream,
                ContentType = metaData.ContentType
            };
        }

        public async Task<StoreFileResult> StoreFile(StoreFileRequest storeFileRequest)
        {
            var fileBytes = Convert.FromBase64String(storeFileRequest.FileDataBase64);

            try
            {
                var fileObject = await storageClient.UploadObjectAsync(
                    bucket: options.BucketName,
                    objectName: storeFileRequest.FileName,
                    contentType: storeFileRequest.ContentType,
                    source: new MemoryStream(fileBytes),
                    options: new UploadObjectOptions { PredefinedAcl = PredefinedObjectAcl.Private }
                );

                if (fileObject == null)
                {
                    throw new Exception("Failed to upload file");
                }
            }
            catch (Google.GoogleApiException ex)
            {
                Console.WriteLine($"Error uploading file {storeFileRequest.FileName}: {ex.Message}");

                return new StoreFileResult()
                {
                    Success = false,
                    ErrorMessage = ex.Message,
                    ErrorHttpStatusCode = ex.HttpStatusCode
                };
            }
            
            return new StoreFileResult()
            {
                Success = true
            };
        }

        public async Task DeleteFileAsync(string fileName)
        {
            try
            {
                await storageClient.DeleteObjectAsync(options.BucketName, fileName);
            }
            catch (GoogleApiException e)
            {
                if (e.Error == null || e.Error.Code != 404)
                {
                    throw;
                }
            }
        }
    }
}

this causes the error

Exception: Object reference not set to an instance of an object. Stack Trace:    at System.Object.GetType()
   at [email protected](SyntaxNode node)
   at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at cs2fs.FSharpOutput.getExprIndentIfMultiline@304[a](FSharpFunc`2 errorPrinter, FSharpFunc`2 f, Expr`1 e)
   at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at cs2fs.FSharpOutput.getExprIndentIfMultiline@304[a](FSharpFunc`2 errorPrinter, FSharpFunc`2 f, Expr`1 e)
   at cs2fs.FSharpOutput.getExprMNP@320[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at cs2fs.FSharpOutput.getExprIndentIfMultiline@304[a](FSharpFunc`2 errorPrinter, FSharpFunc`2 f, Expr`1 e)
   at cs2fs.FSharpOutput.getMatch@171[a](FSharpFunc`2 errorPrinter, a tupledArg0, Pat`1 tupledArg1, FSharpOption`1 tupledArg2, Expr`1 tupledArg3)
   at [email protected](Tuple`4 m)
   at Microsoft.FSharp.Collections.Internal.IEnumerator.map@74.DoMoveNext(b& curr)
   at Microsoft.FSharp.Collections.Internal.IEnumerator.MapEnumerator`1.System-Collections-IEnumerator-MoveNext()
   at Microsoft.FSharp.Collections.SeqModule.ToList[T](IEnumerable`1 source)
   at cs2fs.FSharpOutput.delimLineText(String sep, IEnumerable`1 xs)
   at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at cs2fs.FSharpOutput.getExprNP@319[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at [email protected](Expr`1 e)
   at Microsoft.FSharp.Collections.Internal.IEnumerator.map@74.DoMoveNext(b& curr)
   at Microsoft.FSharp.Collections.Internal.IEnumerator.MapEnumerator`1.System-Collections-IEnumerator-MoveNext()
   at Microsoft.FSharp.Collections.SeqModule.ToList[T](IEnumerable`1 source)
   at cs2fs.FSharpOutput.delimLineText(String sep, IEnumerable`1 xs)
   at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at cs2fs.FSharpOutput.getMember@175[a](FSharpFunc`2 errorPrinter, String className, Expr`1 x)
   at Microsoft.FSharp.Collections.Internal.IEnumerator.map@74.DoMoveNext(b& curr)
   at Microsoft.FSharp.Collections.Internal.IEnumerator.MapEnumerator`1.System-Collections-IEnumerator-MoveNext()
   at Microsoft.FSharp.Collections.SeqModule.ToList[T](IEnumerable`1 source)
   at cs2fs.FSharpOutput.lineblock(IEnumerable`1 xs)
   at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at cs2fs.FSharpOutput.getExprNP@319[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at [email protected](Expr`1 e)
   at Microsoft.FSharp.Collections.Internal.IEnumerator.map@74.DoMoveNext(b& curr)
   at Microsoft.FSharp.Collections.Internal.IEnumerator.MapEnumerator`1.System-Collections-IEnumerator-MoveNext()
   at Microsoft.FSharp.Collections.SeqModule.ToList[T](IEnumerable`1 source)
   at cs2fs.FSharpOutput.delimLineText(String sep, IEnumerable`1 xs)
   at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at cs2fs.FSharpOutput.getExprNP@319[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at [email protected](Expr`1 e)
   at Microsoft.FSharp.Collections.Internal.IEnumerator.map@74.DoMoveNext(b& curr)
   at Microsoft.FSharp.Collections.Internal.IEnumerator.MapEnumerator`1.System-Collections-IEnumerator-MoveNext()
   at Microsoft.FSharp.Collections.SeqModule.ToList[T](IEnumerable`1 source)
   at cs2fs.FSharpOutput.delimLineText(String sep, IEnumerable`1 xs)
   at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at cs2fs.FSharpOutput.getExpr@218[a](FSharpFunc`2 errorPrinter, Expr`1 e)
   at cs2fs.Convert.convertText(String csharp)
   at Server.Result.attempt[a](FSharpFunc`2 f) in /build/src/Server/Server.fs:line 24

Some issues I have found in a real life example

File: https://github.com/dotnet/roslyn/blob/master/src/Compilers/Core/Portable/CvtRes.cs

Issues:

  • using BYTE = System.Byte; should probably be type BYTE = System.Byte instead of open System.Byte
  • sizeof(DWORD) currently UnknownNode should be sizeof<DWORD>
  • Property intitializer:
    new RESOURCE()
                  {
                      HeaderSize = cbHdr,
                      DataSize = cbData
                  };
    
  • do-while loop
    do
                  {
                      sb.Append(curChar);
                      curChar = fhIn.ReadChar();
                  }
                  while (curChar != 0);
    
  • Binary negate operator: stream.Position <- stream.Position + 3 & ~3 -> ERROR UnknownPrefixOperator "~"
  • Generates raise new ResourceException(CodeAnalysisResources.CoffResourceInvalidSectionSize), which doesn't compile as parethesis are required (or <|)

Probably more, I'll edit as needed and might fix some of them.

Conversion fails

#This conversion is not working code in .Net Core 6

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using System.IO;
using System.Threading.Tasks;

namespace LargeFilesSample.Controllers
{
    /// <summary>
    /// controller for upload large file
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class FileUploadController : ControllerBase
    {
        private readonly ILogger<FileUploadController> _logger;

        public FileUploadController(ILogger<FileUploadController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// Action for upload large file
        /// </summary>
        /// <remarks>
        /// Request to this action will not trigger any model binding or model validation,
        /// because this is a no-argument action
        /// </remarks>
        /// <returns></returns>
        [HttpPost]
        [Route(nameof(UploadLargeFile))]
        public async Task<IActionResult> UploadLargeFile()
        {
            var request = HttpContext.Request;

            // validation of Content-Type
            // 1. first, it must be a form-data request
            // 2. a boundary should be found in the Content-Type
            if (!request.HasFormContentType ||
                !MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaTypeHeader) ||
                string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value))
            {
                return new UnsupportedMediaTypeResult();
            }

            var reader = new MultipartReader(mediaTypeHeader.Boundary.Value, request.Body);
            var section = await reader.ReadNextSectionAsync();

            // This sample try to get the first file from request and save it
            // Make changes according to your needs in actual use
            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition,
                    out var contentDisposition);

                if (hasContentDispositionHeader && contentDisposition.DispositionType.Equals("form-data") &&
                    !string.IsNullOrEmpty(contentDisposition.FileName.Value))
                {
                    // Don't trust any file name, file extension, and file data from the request unless you trust them completely
                    // Otherwise, it is very likely to cause problems such as virus uploading, disk filling, etc
                    // In short, it is necessary to restrict and verify the upload
                    // Here, we just use the temporary folder and a random file name

                    // Get the temporary folder, and combine a random file name with it
                    var fileName = Path.GetRandomFileName();
                    var saveToPath = Path.Combine(Path.GetTempPath(), fileName);

                    using (var targetStream = System.IO.File.Create(saveToPath))
                    {
                        await section.Body.CopyToAsync(targetStream);
                    }

                    return Ok();
                }

                section = await reader.ReadNextSectionAsync();
            }

            // If the code runs to this location, it means that no files have been saved
            return BadRequest("No files data in the request.");
        }
    }
}

##Converting like below

open Microsoft.IdentityModel.Tokens

open Microsoft.Extensions.Logging

open Microsoft.Extensions.Configuration

open Microsoft.AspNetCore.Http
open Microsoft.AspNetCore.Mvc
open Microsoft.AspNetCore.WebUtilities
open Microsoft.Extensions.Logging
open Microsoft.Net.Http.Headers
open System.IO
open System.Threading.Tasks

[<ApiController>]
[<Route("[controller]")>]
type FileUploadController(configuration : IConfiguration, logger : ILogger<UserAccountController>,
    tokenValidationParams: TokenValidationParameters) as self =
    inherit SootchyControllerBase(configuration, logger)

    [<HttpPost>]
    [<HttpPost("Upload")>]
    member this.UploadLargeFile() = 
        let mutable request = HttpContext.Request
        if not request.HasFormContentType || not (MediaTypeHeaderValue.TryParse (request.ContentType, (* ERROR UnknownNode "DeclarationExpressionSyntax" var mediaTypeHeader *))) || string.IsNullOrEmpty (mediaTypeHeader.Boundary.Value)
        then return new UnsupportedMediaTypeResult()
        let mutable reader = new MultipartReader(mediaTypeHeader.Boundary.Value, request.Body)
        let mutable section = (* ERROR UnknownNode "AwaitExpressionSyntax" await reader.ReadNextSectionAsync() *)
        while (section <> Unchecked.defaultof<_>) do
            let mutable hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse (section.ContentDisposition, (* ERROR UnknownNode "DeclarationExpressionSyntax" var contentDisposition *))
            if hasContentDispositionHeader && contentDisposition.DispositionType.Equals ("form-data") && not (string.IsNullOrEmpty (contentDisposition.FileName.Value))
            then 
                let mutable fileName = Path.GetRandomFileName ()
                let mutable saveToPath = Path.Combine ((Path.GetTempPath ()), fileName)
                let __ = 
                    use targetStream = System.IO.File.Create (saveToPath)
                    (* ERROR UnknownNode "AwaitExpressionSyntax" await section.Body.CopyToAsync(targetStream) *)
                return (Ok ())
            section <- (* ERROR UnknownNode "AwaitExpressionSyntax" await reader.ReadNextSectionAsync() *)
        BadRequest ("No files data in the request.")

image

Simplify class conversion

Screenshot 2022-09-02 at 15 40 54

This conversion seems way more verbose than what it could be,

e.g. just

type TestMe(test: string, another: int) =
      begin
      end class

Probably the class gen approach can be simplified as constructor arguments in F# are already private readonly implicitly, making the code more succint

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.