Skip to content

Instantly share code, notes, and snippets.

@jamessdixon
Created August 31, 2018 12:17
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamessdixon/f253cb28f16b568b34741cba23f6a0a1 to your computer and use it in GitHub Desktop.
Save jamessdixon/f253cb28f16b568b34741cba23f6a0a1 to your computer and use it in GitHub Desktop.
Convert Auto-Generatd C# classes to F# Types
open System
open System.IO
open System.Collections.Generic
let path = @"C:\Git\..."
let folderInfo = System.IO.DirectoryInfo(path)
let files = folderInfo.GetFiles("*.cs")
let parseClass (values: IEnumerable<string>) =
let className =
values
|> Seq.filter(fun l -> l.Contains("public class"))
let typeName =
match className |> Seq.length with
| 0 -> None
| _ -> Some (className |> Seq.head)
let propNames =
values
|> Seq.filter(fun l -> l.Contains("{ get; set; }"))
typeName, propNames
let createTypeName (className:string option) =
match className with
| Some cn ->
let typeName = cn.Replace(" public class"," ").Trim()
match(typeName.Contains("Configuration")) with
| true -> None
| false -> Some typeName
| None -> None
let reverseValues (typeAttribute:string) =
let tokens = typeAttribute.Split(' ')
match tokens.Length with
| 0 | 1 -> ""
| _ -> tokens.[1] + ":" + tokens.[0]
let createTypeAttributes (items: IEnumerable<string>) =
let temp =
items
|> Seq.map(fun i -> i.Replace("public",""))
|> Seq.map(fun i -> i.Replace("{ get; set; }",""))
|> Seq.map(fun i -> i, i.IndexOf("//"))
|> Seq.filter(fun (i,t) -> t > 0)
|> Seq.map(fun (i,t) -> i.Substring(0,t))
|> Seq.map(fun i -> i.Trim())
|> Seq.map(fun i -> reverseValues i)
match Seq.length temp with
| 0 -> ""
| _ -> Seq.reduce(fun acc elem -> acc + ";" + elem) temp
let createType (values:string option * IEnumerable<string>) =
createTypeName(fst values),
createTypeAttributes (snd values)
let printType (typeName:string) (typeAttributes: string) =
printfn "type %s {%s}" typeName typeAttributes
files
|> Array.map(fun f -> f.FullName)
|> Array.map(fun fn -> fn, File.ReadLines(fn))
|> Array.map(fun (fn,c) -> parseClass c)
|> Array.map(fun x -> createType x)
|> Array.filter(fun (x,y) -> x.IsSome)
|> Array.map(fun (x,y) -> x.Value, y)
|> Array.iter(fun (x,y) -> printType x y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment