I have a WebApi written in F# and I need to add some more fields to the record it transmits and accepts. Data is transmitted as Json using the Newtonsoft.Json library.
This is the record:
[<DataContract(Name="Foo")>]
[<CLIMutable>]
type Foo =
{
[<DataMember>] Name: String
[<DataMember>] Time: DateTimeOffset
[<DataMember>] Status : String
[<DataMember>] Newfield : int64 array // new
[<DataMember>] OptionalField : DateTimeOffset option // new
}
So the Json I'm receiving from looks like
{
"Name":"Bob",
"Time":"2017-12-22 06:00:00",
"Status":"OK",
}
With the new fields missing. With the OptionalField it may be purposefully omitted.
However when this gets deserialized, Newfield & OptionalField are set to null, which is bad in F# land.
let! content = this.Request.Content.ReadAsStringAsync() |> Async.AwaitTask
let foo = JsonConvert.DeserializeObject<Foo>(content)
What ability do I have to populate the field with either and Empty array or None?
Obviously in this case I could just inspect the created item and fix it, but this is just an example of a wider problem. I'd like some kind of generic solution that can be applied in one place (a JsonConverter, attributes on the new members etc) - rather than needing to inspect every field it should be fixed after deserializing.
Related
I want to query to get a string, for which I have to provide a input object, however the input data can have multiple optional keys and quite grow large as well. So I just wanted something like Object as data type while defining schema.
// example of supposed schema
input SampleInput {
id: ID
data: Object // such thing not exist, wanted something like this.
}
type Query {
myquery(input: SampleInput!): String
}
here data input can be quite large so I do not want to define a type for it. is there a way around this?
I'm trying to construct a stream pipeline which is not really straightforward and it gets me puzzled.
The idea is that I have a class containing a set of entities I want to traverse. Application class defines a field Set<Document> documents. Inside of these docs I have a field DocumentFile documentFile. I filter the stream based on the name of this document file, but the result that I need is the id of Document entity.
So the method goes like this:
private long retrieveSmth(String docName, long applicationId) {
final Application application = this.applicationDao.get(applicationId);
final long docId = application.getDocuments()
.stream()
.map(Document::getDocumentFile)
.filter(doc -> doc.getDocumentFileName().equals(docName))
...
}
At this point I get stuck questioning myself how do I get the control back to Document level and retrieve the id of the document whose document file satisfies the condition. Is there a way to do this using Stream API?
If you map() to DocumentFile you cannot "go back" to the owner object of DocumentFile : the Stream<Document> was transformed into a Stream<DocumentFile>.
You should so not map and specify the object to test from Stream<Document>.filter() :
final long docId = application.getDocuments()
.stream()
.filter(doc -> doc.getDocumentFile().getDocumentFileName().equals(docName))
.map(Document::getId); // now it is possible
Note that you should avoid talking to strangers and this makes this bad smell :
doc.getDocumentFile().getDocumentFileName()
So it would be interesting to introduce a method matchesName() in Document that does the delegation and the equality test :
public boolean matchesName(String name){
return name.equals(getDocumentFile().getDocumentFileName());
}
In this way it sounds better :
.filter(doc -> doc.matchesName(docName))
Hello guys i am using this code to fetch the Result from Coredata
func getRequest(entiryDesc:NSEntityDescription) -> NSFetchRequest{
var request:NSFetchRequest = NSFetchRequest()
request.entity = entiryDesc
request.resultType = NSFetchRequestResultType.DictionaryResultType
return request
}
Now the problem is i need All the attributes which contains the Nil value too but the excutefetchrequest returns only those properties which have values , is there any work around for this to return Null attributes with String like "" every time i fetch ? Thanks Advanced
Of course, you can just dispense with the .DictionaryResultType and fetch normal managed objects. There are very few cases where the dictionary result type makes sense.
If you want to construct a dictionary with all attributes filled out (for whatever opaque reason), remember two things:
Make sure to insert the null values as objects NSNull()
You can use the NSEntityDescription API to generate all the attribute keys. Use entityDescription.propertiesByName.allKeys to generate a list of all attribute names of your entity.
Being new to attribute routing, I'd like to ask for help getting this to work.
This test is a simple dynamic DB table viewer: Given a table name (or stored query name or whatever) and optionally some WHERE parameters, return query results.
Table COMPANIES (one of any number of tables which has an associated SELECT query stored somewhere, keyed by table name):
ID NAME HQ INDUSTRY
1 Apple USA Consumer electronics
2 Bose USA Low-quality, expensive audio equipment
3 Nokia FIN Mobile Phones
Controller:
[Route("view/{table}/{parameters}")]
public object Get(string table, Dictionary<string, string> parameters) {
var sql = GetSql(table);
var dbArgs = new DynamicParameters(parameters);
return Database.Query(sql, dbArgs); // Return stuff/unrelated to problem
}
SQL stored in some resource or table. Obviously the parameters must match exactly:
SELECT * FROM companies
WHERE name = :name
-- OR hq = :hq
-- OR ...etc. Doesn't matter since it never gets this far.
Request (Should look clean, but the exact URL format isn't important):
www.website.com/view/companies?hq=fin --> 404: No matching controller
www.website.com/view/companies/hq=fin --> parameters is null
www.website.com/view/companies/hq=fin&name=nokia --> Exception: A potentially dangerous Request.Path value was detected from the client (&).
When I use: [Route("view/{table}{parameters}")] I get:
A path segment cannot contain two consecutive parameters. They must be separated by a '/' or by a literal string. Parameter name: routeTemplate. Makes sense.
My question is: How do I accept a table name and any number of unknown parameters in the usual key1=val1&key2=val2 form (not some awkward indexed format like the one mentioned here) which will be later bound to SQL parameters, preferably using a vanilla data structure rather than something like FormCollection.
I don't think that binding URL parameters to a Dictionary is built-in to the framework. I'm sure there's a way to extend it if you wanted to.
I think quickest (but still acceptable) option is to get the query string parameters using Request.GetQueryNameValuePairs() like this:
[Route("view/{table}")]
public object Get(string table) {
Dictionary<string, string> parameters = Request.GetQueryNameValuePairs()
.ToDictionary(x => x.Key, x => x.Value);
var sql = GetSql(table);
var dbArgs = new DynamicParameters(parameters);
return Database.Query(sql, dbArgs); // Return stuff/unrelated to problem
}
I've thrown myself headfirst into C# and .Net 2.0 using Linq, and I'm having a few problems debugging some of the problems, namely the following:
I have a ComboBox control (cmbObjects) I want to populate with a set of objects retrieved using Linq. I've written a helper method to populate a List<T> generic:
class ObjectProvider
{
public static List<T> Get<T>(bool includeNull) where T : class, new()
{
List<T> list = new List<T>();
LutkeDataClassesDataContext db = ConnectionManager.GetConnection();
IQueryable<T> objects = db.GetTable<T>().AsQueryable();
if (includeNull) list.Add(null);
foreach (T o in objects) list.Add(o);
return list;
}
public static List<T> Get<T>() where T : class, new()
{
return Get<T>(false);
}
}
I verified the results when calling the function with true or false - the List does contain the right values, when passing true, it contains null as the first value, followed by the other objects.
When I assign the DataSource to the ComboBox however, the control simply refuses to display any items, including the null value (not selectable):
cmbObjects.DataSource = ObjectProvider.Get<Car>(true);
Passing in false (or no parameter) does work - it displays all of the objects.
Is there a way for me to specify a "null" value for the first object without resorting to magic number objects (like having a bogus entry in the DB just to designate a N/A value)? Something along the lines of a nullable would be ideal, but I'm kind of lost.
Also, I've tried adding new T() instead of null to the list, but that only resulted in an OutOfMemoryException.
The combo box control has an option to append data bound items to the hard-coded items in the list. So you hard-code your n/a value, and data bind the real values.
Okay, it seems the DataSource becomes invalid if you try to add a null value. The solution was to just add the items via a simple foreach loop with an empty string at the start instead of assigning the List<>.