Snippets in category .NET Libraries
Friendly date formatting
Generates a friendly string describing a date relatively to the current date and time. The function returns strings like "2 secs ago", "yesterday" or "3 years ago".
26 people like this
Posted: 1 years ago by Tomas PetricekNice formatting of type names
Add extension to System.Type that returns the name of type including generic arguments in a nice readable format. It returns only short names of generic type and type arguments.
13 people like this
Posted: 1 years ago by Tomas PetricekConvert an object to json, and json to object
There is a namespace System.Runtime.Serialization.Json To serialize generic object you can do like this...
40 people like this
Posted: 1 years ago by Tuomas HietanenGetting a key from Windows registry
F# code to fetch a registry key
16 people like this
Posted: 1 years ago by Tuomas HietanenDecrypting a Rijndael string
This F# code decrypts an encrypted string using Rijndael symmetric encryption algorithm. It uses key and initialization vector stored in a registry key.
34 people like this
Posted: 1 years ago by Tuomas HietanenFunctions around nullable types
Various functions around nullable types
12 people like this
Posted: 1 years ago by Mauricio SchefferCalculating Age
This function interprets a time span in terms of years, months and days.
23 people like this
Posted: 1 years ago by Taha HachanaCreate generic IEnumerable from non-generic
Depends on Castle Dynamic Proxy 2. Returns an IEnumerable<T> from a System.Type and a System.Collections.IEnumerable. It is a hack I wrote simply because I couldn't find anything in the framework to do this.
19 people like this
Posted: 1 years ago by Dan FinchConvert a obj list to a typed list without generics
This is used for building things with reflection at runtime. As ConstructorInfo arguments require typed collections, it is necessary when parsing to reflected records to first build up contents and then afterward convert the collected obj[] to a 'a[]. This is finally cast back to obj so it can be used as a ConstructorInfo argument.
18 people like this
Posted: 1 years ago by Rick MinerichComposable WCF Web API using Async
A functional wrapper around the new WCF Web APIs (http://wcf.codeplex.com/). Composition is achieved through the use of the HttpRequestMessage -> Async<HttpResponseMessage> signature. Pushing the app calls in the MessageHandler intercepts all requests and allows you to take control at the earliest point possible before operation selection occurs. Extending this slightly to call the innerChannel's SendAsync would allow you to create a middleware layer that would work both with this and other, normal Web API services.
39 people like this
Posted: 1 years ago by Ryan RileyFind verbose .NET types using Reflection
Searches all (currently loaded) types using Reflection to find the types with longest and shortest names of members. Uses average length of all type member names as a metric.
8 people like this
Posted: 1 years ago by Tomas PetricekDisposable computation builder
Computation builder that provides easy way of constructing IDisposable objects. It supports elegant composition of disposable objects using 'do!' which can be used for example when working with 'IObservable' type.
27 people like this
Posted: 1 years ago by Tomas PetricekPalindromic dates
Today, 11. february 2011, is a palindromic day according to the European date format (day/month/year). This snippet collects all the palindromic dates until 31 dec. 9999. They are 366, a surprisingly low number.
12 people like this
Posted: 1 years ago by Francesco De VittoriObservable.Subject
The Subject<T> type implements both IObserver<T> and IObservable<T>. It is functionally equivalent to the type of the same name in the Reactive Extensions (Rx) library.
13 people like this
Posted: 1 years ago by Phillip TrelfordUgly hack to call F# functions as static methods
Ugly hack to call F# functions as static methods
3 people like this
Posted: 1 years ago by fholmSimple Object orientation using Record types
Simple Object orientation using Record types. No complex - private public internal virtual abstract object oriented programming :)
5 people like this
Posted: 1 years ago by Ankur DhamaSerialization of functions
Serialization and deserialization of a function value with Soap formatting. (With serious limitations; not sure how useful this is.)
4 people like this
Posted: 1 years ago by wmeyerDynamic operator using Dynamic Language Runtime
The snippet shows a simple implementation of the dynamic operator (?) that uses Dynamic Language Runtime and the C# implementation of dynamic operations. The snippet shows how to invoke instance methods with single argument.
25 people like this
Posted: 1 years ago by Tomas PetricekDynamic operator using Reflection
Demonstrates how to implement the dynamic operator (?) using .NET Reflection. The implementation supports calling constructors, propreties and methods using simple overload resolution (based on parameter count). It handles instance as well as static members.
41 people like this
Posted: 1 years ago by Tomas PetricekString repeater
A function that efficiently creates a new string containing a given string multiple times. The function is implemented using .NET StringBuilder class.
8 people like this
Posted: 1 years ago by fholmPerl Style "Regex Matches?" operator
Perl Style "Regex Matches?" operator
35 people like this
Posted: 1 years ago by fholmCreate Disposable
This pattern is helpful when you want to do something temporarily and then restore some state. This was inspired by the System.Disposable.Disposable() class defined in System.Core.dll distributed by the Reactive Extensions for .NET (Rx) library.
26 people like this
Posted: 1 years ago by Cesar MendozaBar chart using chart controls
The snippet shows how to use Microsoft Chart Controls (available in .NET 4.0 and for .NET 3.5) to draw a Bar chart. The sample shows population sizes in different continents.
17 people like this
Posted: 1 years ago by Tomas PetricekDoughnut chart using chart controls
The snippet shows how to use Microsoft Chart Controls (available in .NET 4.0 and for .NET 3.5) to draw a Doughnut chart. The sample shows proportion of seats taken by parties in UK elections.
46 people like this
Posted: 1 years ago by Tomas PetricekLine chart using chart controls
The snippet shows how to use Microsoft Chart Controls (available in .NET 4.0 and for .NET 3.5) to draw a Line chart. The sample generates a 2D spline calculated using sin and cos functions.
9 people like this
Posted: 1 years ago by Tomas PetricekCandlestick chart using chart controls
The snippet shows how to use Microsoft Chart Controls (available in .NET 4.0 and for .NET 3.5) to draw a Candlestick chart visualizing stock prices. The sample uses price of MSFT stocks over 20 days.
9 people like this
Posted: 1 years ago by Tomas PetricekBoxplot diagram using chart controls
The snippet shows how to use Microsoft Chart Controls (available in .NET 4.0 and for .NET 3.5) to draw a BoxPlot diagram. In this sample, we provide six statistics (Maxmimum, Minimum, Upper quartile, Lower quartile, Average and Median) about observations explicitly.
14 people like this
Posted: 1 years ago by Tomas PetricekSplit a list
Three ways to split a list in half (but not necessarily in the middle). A forth version added that's very short and should be fast, as we only use List.fold. New champ found.
48 people like this
Posted: 1 years ago by Dmitri PavlenkovFunctional XML Construction and Query
This snippet shows how to construct and query XML using XLinq without too many helper functions.
17 people like this
Posted: 1 years ago by Taha HachanaCompiler Regression in VS2010-SP1
Compiler regression in VS2010-SP1 ?
21 people like this
Posted: 1 years ago by fholmType-a-head search tree for strings
This is a search tree for strings I've built for work to back fast type-a-head for AJAX forms, it could be made million times more space efficient but there was no real need for it so.
3 people like this
Posted: 1 years ago by fholmHosting the DLR with IronPython or Ruby
Definition of the dynamic resolution operators for hosting the DLR. You can either use Ruby or Python, as the module isn't language specific.
3 people like this
Posted: 1 years ago by Rainer SchusterCSV reader
I've modified the CSV sample from Expert F# to my needs. I don't wann be forced to use the csv schema as defined by column rows. Therefore I've done two major modifications. 1. remove the permutation 2. added a new column name option to the ColumnAttribute 3. added a name to csv index mapping So basically you now have 3 options. 1. Don't annotate your record at all and use it as POCO. The order of the record fields is mapped directly to the order in the csv. UPDATE: I don't recommend this any more. As of the writing of this snippet I wasn't aware of the fact, that field order isn't guaranted by the reflection mechanism. 2. Use the index option of the ColumnAttribute. Same as before. 3. Use the name option. This is what I've looked for. I've to deal with tons of csv that has more columns I'm interested in. Have a look at the sample usage below. I've moved the type conversion out of the CsvReader class in order to be easyly expandable with custom type conversation (i.e. for combined column values - denormalized data)
4 people like this
Posted: 1 years ago by Rainer SchusterCSV writer
A simple CSV writer implementation as two type extensions for the Seq module. Use it with Records, Classes and Tuples. Have a look at the modified CSV reader sample from Don Symes Expert F# too http://fssnip.net/3T in order to advance this snippet using the ColumnAttribute
3 people like this
Posted: 1 years ago by Rainer SchusterNullable Refs without using AllowNullLiteral
Nullable Refs without using AllowNullLiteral
3 people like this
Posted: 1 years ago by fholmResource cleanup event combinator
Declares an event combinator 'Event.using' that automatically releases resources allocated by a previous event occurence. Each event occurence creates a value using a function specified by the user and automatically calls 'Dispose' when generating a new value.
2 people like this
Posted: 1 years ago by Tomas PetricekNullable to Option
it's allways a pain to work with F#'s Option values outside of F# - there you've got the Nullable-class this is a short snippet to convert Nullable<'a> to 'a option
2 people like this
Posted: 1 years ago by Carsten König
Rope
Simple implementation of the rope data structure, http://en.wikipedia.org/wiki/Rope_(computer_science)
2 people like this
Posted: 1 years ago by fholmFholm
Fast Concatenated String
2 people like this
Posted: 1 years ago by fholmEfficient Immutable String Concat
Efficient Immutable String Concat
4 people like this
Posted: 1 years ago by fholmstore yahoo quotes in kdb
This snippet will download the constituents from ftse, stoxx50e,dji,hsi,gspc and store quotes beginning from 1981 into kdb. To get this to work you need to download kpnet from http://kpnet.codeplex.com/ and kdb.
1 people like this
Posted: 1 years ago by Kim TangFactorial using Int64, Double and BigInteger
Recursive Factorial using Int64, Double and BigInteger with execution time.
0 people like this
Posted: 1 years ago by Carlos QuintanillaTimestamp with timezone (YYYYMMDDhhmmssffff+zzzz)
Timestamp: Time format in ISO 8601 with timezone. YYYYMMDDhhmmssffff+zzzz For example 2011-05-17 19:01:10.000 -0200 would be: 20110517190110000-0200
2 people like this
Posted: 1 years ago by Tuomas HietanenSimple F# ViewModel for Silverlight MVVM
Silverlight default architecture is Model-View-ViewModel. This code gives full design time support for Microsoft Expression Blend. The F# ViewModel is seen as strongly typed data source in the Blend UI. There are two properties binded to the view: HiLabel (OneWay data binding) and MyName (TwoWay data binding). ViewModel implements the INotifyPropertyChanged to support the binding. The view project (HelloApp) is made with Blend (by designers) and it is Silverlight 5.0 project. The view codebehind is c# file and it has only this.DataContext -assignment. The viewmodel project (HelloApp.ViewModel) is F# Silverlight 4.0 library. It is made with VS2010 and F# (by developers). It contains the logical functionality of the current view.
4 people like this
Posted: 11 months ago by Tuomas HietanenReplaySubject
The ReplaySubject<T> type implements both IObserver<T> and IObservable<T>. It is functionally equivalent to the class of the same name in the Reactive Extensions (Rx) library with a replay buffer of a specified size .
1 people like this
Posted: 11 months ago by Phillip TrelfordString explode and implode
Convert string to and from character lists.
3 people like this
Posted: 11 months ago by petebuActive pattern for comparison
An active pattern for comparing two objects of the same type and implementing IComparable. Modeled on Standard ML comparison.
4 people like this
Posted: 11 months ago by petebuAgent based ObjectPool
This is a simple implementation of an object pool using an agent (MailboxProcessor). The pool is created with an initial number of object using the specified generator. The ObjectPool has three functions: Put: An item can be 'Put' into the pool. Get: An item can be taken from the pool ToListAndClear: A list of all the items in the pool is returned and the pool is cleared.
7 people like this
Posted: 11 months ago by 7sharp9escaping string
escaping string, very terse . Update: a bit more terse, and perf improvement by using .ToCharArray() and Array.iter
1 people like this
Posted: 11 months ago by hammettSimple string escaping
Simple string escaping.
5 people like this
Posted: 11 months ago by fzandonaWimbledon special!
Tennis scoring system (at the game level). Includes some pattern-matching examples including 'when' guards.
4 people like this
Posted: 10 months ago by Kit EasonExtensions for HTTP servers
This snippet extends several types from the System.Net namespace. It provides an easy to use API for creating asynchronous (as well as synchronous) HTTP servers using F# asynchronous workflows.
3 people like this
Posted: 10 months ago by Tomas PetricekUnion-Friendly Generic Binary Serializer
Implements binary serialization. The encoding supports all records, unions, numeric types, strings, rank-1 arrays, maps, sets, lists and dictionaries. Strings are interned for efficiency. The encoding also uses binary compression (GZIP).
5 people like this
Posted: 10 months ago by Anton TayanovskyyCreating observable using Async.StartDisposable
Implements a simple Async.StartDisposable extension that can be used to easily create IObservable values from F# asynchronous workflows. The method starts an asynchronous workflow and returns IDisposable that cancels the workflow when disposed.
4 people like this
Posted: 8 months ago by Tomas PetricekSliding window for Observable
Implements the Observable.windowed function that creates an observable returning a sliding window. The function is an observable version of Seq.observable. The implementation uses a simple F# agent that keeps partial windows and sends them to an observer.
3 people like this
Posted: 8 months ago by Tomas PetricekGet the F# module or type of the calling code.
This code snippet enables the retrieval of the entity (Module or F# Type) in which the calling code is executing. This can be used to find the module or type name.
2 people like this
Posted: 8 months ago by Huw Simpsoncsproj-file parsing with Linq2Xml
This program reads all *.csproj-files from a path and then uses Linq2Xml to show data about the projects. This should be a good template for scripts to manage tons of c#-project files. F# and LINQ-to-XML is very powerful combination.
6 people like this
Posted: 7 months ago by Tuomas HietanenJSON Parser
JSON Parser using Regular Expressions & Active Patterns (just for fun).
5 people like this
Posted: 7 months ago by Phillip TrelfordConcatenate two strings together
Concatenates two strings together: ML or OCaml style
2 people like this
Posted: 6 months ago by Cameron FrederickHuman Date
Datetime Readable for Humans, Ported from Clojure https://github.com/pmn/noir-messageboard/blob/master/src/noir_messageboard/utils/utils.clj
23 people like this
Posted: 6 months ago by christophdUniversity enrollment (CZE vs. EU)
Using World Bank type provider and FSharpChart to show average university enrollment in Czech Republic, European Union and OECD members.
6 people like this
Posted: 6 months ago by Tomas PetricektoString and fromString for discriminated unions
General toString and fromString for discriminated unions using FSharp.Reflection
16 people like this
Posted: 5 months ago by Jonas AvelinForking console output to a string
Higher order function 'withOutStr' to fork console output to a string. The function temporarily redirects Console.Out to a custom TextWriter
4 people like this
Posted: 5 months ago by Jonas AvelinObservable Async Subject
Simple Async Observable Subject<'T> based on MailboxProcessor. Type declaration is more ML like, but the idea is represented in a simple way!
4 people like this
Posted: 5 months ago by FahadTransform expressions into Excel formulae
Sometimes it is extremely useful to check some calculations with Excel. The snippet shows how F# expressions can be transformed into Excel formulae. The data is exported together with the formulae, e.g. a, b and sum function as input sets A1's value to a, B1's to b and C1's formula to "=$A$1+$B$1"
14 people like this
Posted: 4 months ago by Natallie BaikevichSave attachments from exchange inbox
Save the attachments of the first 10 mails to disk
1 people like this
Posted: 3 months ago by Joeri Belisread CSV with .net FileHelpers library
example to use the open source .net FileHelpers library to read a CSV ( http://filehelpers.sourceforge.net/ ). csv example with no exception error field1,field2,field3 123,123,aaa 456,123,aaa example with exception where the functions returns an empty array field1,field2,field3 123,aaa,aaa 456,123,aaa
2 people like this
Posted: 3 months ago by Joeri BelisFactoring out FSharpChart
Using FSharpChart control. Just call Charting.Plot() to chart series or collections of series. No need to create forms, etc.
2 people like this
Posted: 2 months ago by Boris Kogancsproj-file parsing with Linq2Xml - part 2
This program reads all *.csproj-files from a path and then uses Linq2Xml to show or modify data about the projects. This should be a good template for scripts to manage tons of c#-project files. F# and LINQ-to-XML is very powerful combination.
7 people like this
Posted: 2 months ago by Tuomas Hietanenreflection
reflection, not exactly efficient but good canvas to start exploring
5 people like this
Posted: 1 months ago by David KleinBuilding Strings
When sprintf and String.concat is either too slow or not really what is needed, one can use System.Text.StringBuilder. This snippet makes working with StringBuilder much more convenient and the resulting code more succint.
1 people like this
Posted: 1 months ago by Bent RasmussenSimple builder example: Nullable
Simple Computational expressions / monad / builder -example, using .NET Nullable as demo.
3 people like this
Posted: 28 days ago by Tuomas HietanenHow to Serialize Record, Discriminated Union and Tuple in Azure?
Here is the implementation of the three types in WCF Azure, and a sample using WCF in worker role, a WPF test project to invoke the three kinds of data type from worker role. Link is http://fsharp3sample.codeplex.com/SourceControl/changeset/view/13524
0 people like this
Posted: 35 mins ago by AndrewXue