F# WebAPI default deserialization producing # sign - f#

I'm working on an F# Web API application - https://github.com/odytrice/Dumia
When I try to send an Array of the following records,
[<CLIMutable>]
type Product =
{ ProductID : int
Code : string
Name : string
Price : decimal
ImageUrl : string }
[<CLIMutable>]
type Inventory =
{ Product: Product
Quantity: int }
Here is my current WebAPI Configuration
let registerWebApi (app:IAppBuilder) =
let config = new HttpConfiguration()
// Configure routing
config.MapHttpAttributeRoutes()
// Remove XML Formatter
config.Formatters.Clear()
let formatter = new JsonMediaTypeFormatter()
formatter.UseDataContractJsonSerializer <- false
config.Formatters.Add(formatter)
config.Services.Replace(typeof<IHttpControllerActivator>, CompositionRoot())
app.UseWebApi(config)
My Web API is producing the following output
{
Product#: {
ProductID#: 1,
Code#: "Bag-01",
Name#: "Ladies Bag",
Price#: 120,
ImageUrl#: "/content/images/bag.jpg"
},
Quantity#: 15
}
Does anyone have an idea how to get rid of the # sign?

The Problem is because of the Default DataContract used by WebAPI.
I had to change it to
config.Formatters
.JsonFormatter
.SerializerSettings
.ContractResolver
<- Serialization.DefaultContractResolver()
or better yet
config.Formatters
.JsonFormatter
.SerializerSettings
.ContractResolver
<- Serialization.CamelCasePropertyNamesContractResolver()

Related

How to model an entity with a currency?

I am trying to model a bond entity in F# using a unit of measure for the currency.
type Bond = {
Isin: string
Issuer: string
Maturity: DateTime
Price: float<???>
}
Let's assume that a static table with all the available/possible currencies is available.
type Currency = {
Code : string
Name : string
}
I can go for Price as float and PriceCurrency as string or even as a Currency type but I think that this is not ideal.
Any ideas?
I don't think F# units of measure are a good match for this use case, since the compiler isn't aware of the currency table. If you want to use units of measure anyway, each currency would have to be hard-coded into your source, like this:
open System
[<Measure>] type Dollar
[<Measure>] type Pound
type Bond =
{
Isin: string
Issuer: string
Maturity: DateTime
}
type DollarBond =
{
Bond: Bond
Price: float<Dollar>
}
type PoundBond =
{
Bond: Bond
Price: float<Pound>
}
let poundsPerDollar = 0.73<Pound/Dollar>
let toPoundBond (dollarBond : DollarBond) =
{
Bond = dollarBond.Bond
Price = dollarBond.Price * poundsPerDollar
}
let dollarBond : DollarBond =
{
Bond = {
Isin = "My isin"
Issuer = "My issuer"
Maturity = DateTime.Parse("1/1/2050")
}
Price = 1000.0<Dollar>
}
printfn "%A" <| toPoundBond dollarBond

F#: how to have the variables defined above a XUnit test function actually initialized when running the test?

Following up another question: F#: Why those two collections are not equal? the example below shows that when running Open an account... test id and contact are not initialized.
If there were functions returning the same values and called in the test body it would work though.
I am wondering why this is case, and if there is anything I can do to have those variables properly initialized when the test is running.
let id = Guid.Empty
let contact = {
Name = {
FirstName = "Marcel"
MiddleInitial = None
LastName = "Patulacci"
}
DateOfBith = new DateTime(1850, 12, 25)
Address = {
Address1 = "41 av 8 Mai 1945"
Address2 = None
City = "Sarcelles"
State = None
Zip = "95200"
}
PhoneNumber = {
DialOutCode = 33
LocalNumber = "766030703"
}
Email = "marcel.patulacci#outlook.com"
}
[<Fact>]
let ``Open an account...``() =
let event = Event.AccountOpened({
AccountId = id
Contact = contact
})
let a = [event]
let b = seq { yield event }
Assert.Equal(a, b)
This is down to how F# modules are implemented in .NET IL. Modules are compiled into static classes, and module-defined values are initialized in the class's static constructor. But because of the way XUnit loads tests, the static constructor is not run.
A possible way to circumvent this is to use a class instead of a module, as XUnit does run instance constructors. let functions in a class are compiled to private methods, so the tests are recognized by XUnit without having to switch to member syntax.
type MyTests() =
let id = Guid.Empty
let contact = // ...
[<Fact>]
let ``Open an account...``() =
// ...

I have created one string extension to join string with space in swift 2.0 but its not working in swift 2.1 xcode 7

I am new in swift 2.1 , i have created one extension for string and function name is join, When i converted the code from swift 2.0 to swift 2.1 my code return me error
please help me , i am not able to understand what to do
This is extension
extension String {
func join<S : SequenceType where S.Generator.Element : Printable>(elements: S) -> String {
return self.join(map(elements){ $0.description })
}
}
Here is I am using like this
var channel_string:String!
var languages = [String]()
for var i = 0 ; i < ary_selected_channel.count ; i++
{
let getString_setvalue = ary_selected_channel.objectAtIndex(i) as! String
languages.append(getString_setvalue)
}
channel_string = " ".join(languages)
The output is look like , assume In array i have Three name ["one","two","three"]
then output is
channel_string = "one two three"
The error is
1) Printable has been renamed to customstringconv
2) Type of expression is ambiguous without more context
the error you receive is self-explanatory. by the way, there is easy to do the same without any complication ...
let arr = ["one","two","three"]
let str = arr.joined(separator: " ") // "one two three"

Swift checking String for guid value

I receive from my web service an authorisation string, that represents a Guid (C#). How I can convert string into guid using Swift? Or, how I can validate result, that it is, in fact, a Guid?
var str1:String = "5810744d-49f7-4edc-aefb-ecd1ebf9e59b"
var str2:String = "Some text"
How i can define - is string contains guid?
You can use NSPredicate with a regex to see if a string is in the correct format:
var str1:String = "(5810744d-49f7-4edc-aefb-ecd1ebf9e59b)"
var str2:String = "Some text"
let guidPred = NSPredicate(format: "SELF MATCHES %#", "((\\{|\\()?[0-9a-f]{8}-?([0-9a-f]{4}-?){3}[0-9a-f]{12}(\\}|\\))?)|(\\{(0x[0-9a-f]+,){3}\\{(0x[0-9a-f]+,){7}0x[0-9a-f]+\\}\\})")
// Prints "str1 IS a GUID"
if guidPred.evaluateWithObject(str1) {
println("str1 IS a GUID")
} else {
println("str1 is NOT a GUID")
}
// Prints "str2 is NOT a GUID"
if guidPred.evaluateWithObject(str2) {
println("str2 IS a GUID")
} else {
println("str2 is NOT a GUID")
}
This regex will match any of the four formats listed on MSDN. To keep it (relatively) simple, the expression will match some ill-formatted strings (such as if you were to delete one hyphen, but not all the others: 5810744d49f7-4edc-aefb-ecd1ebf9e59b), but will filter out regular text.

Subtracting Records from a Set using case-insensitive comparison

I have a set of records:
type Person =
{
Name : string
Age : int
}
let oldPeople =
set [ { Name = "The Doctor"; Age = 1500 };
{ Name = "Yoda"; Age = 900 } ]
Unlike the hardcoded example above, the set of data actually comes from a data source (over which I have very little control). Now I need to subtract a set of data from another data source. In general, the data in this second source matches, but occasionally there is a difference in captialization:
let peopleWhoAreConfusedAboutTheirAge =
set [ { Name = "THE DOCTOR"; Age = 1500 } ]
When I attempt to subtract the second set from the first, it fails because the string comparison is case sensitive:
let peopleWhoKnowHowOldTheyAre =
oldPeople - peopleWhoAreConfusedAboutTheirAge
val peopleWhoKnowHowOldTheyAre : Set<Person> =
set [{Name = "The Doctor";
Age = 1500;}; {Name = "Yoda";
Age = 900;}]
Is there a way to perform a case-insensitive comparison for the Name field of the People record?
This is what I've implemented so far, though there may be a better way to do it.
My solution was to override the Equals function on the People record so as to perform a case-insensitive comparison. Set subtraction uses the Equals function to determine if two records match one another. By overriding Equals, I was forced (via warning and error) to override GetHashCode and implement IComparable (as well as set the CustomEquality and CustomComparison attributes):
[<CustomEquality; CustomComparison>]
type Person =
{
Name : string
Age : int
}
member private this._internalId =
this.Name.ToLower() + this.Age.ToString()
interface System.IComparable with
member this.CompareTo obj =
let other : Person = downcast obj
this._internalId.CompareTo( other._internalId )
override this.Equals( other ) =
match other with
| :? Person as other ->
System.String.Compare( this._internalId, other._internalId ) = 0
| _ -> false
override this.GetHashCode() =
this._internalId.GetHashCode()
This, however, seems to do the trick:
let oldPeople =
set [ { Name = "The Doctor"; Age = 1500 };
{ Name = "Yoda"; Age = 900 } ]
let peopleWhoAreConfusedAboutTheirAge =
set [ { Name = "THE DOCTOR"; Age = 1500 } ]
let peopleWhoKnowHowOldTheyAre =
oldPeople - peopleWhoAreConfusedAboutTheirAge
val peopleWhoKnowHowOldTheyAre : Set<Person> = set [{Name = "Yoda";
Age = 900;}]
If you know a better solution (involving less code), please post it rather than comment on this answer. I will happily accept a less verbose, awkward solution.
Here's another approach:
type Name(value) =
member val Value = value
override this.Equals(that) =
match that with
| :? Name as name -> StringComparer.CurrentCultureIgnoreCase.Equals(this.Value, name.Value)
| _ -> false
override this.GetHashCode() =
StringComparer.CurrentCultureIgnoreCase.GetHashCode(this.Value)
type Person =
{
Name: Name
Age: int
}
{Name=Name("John"); Age=21} = {Name=Name("john"); Age=21} //true

Resources