The quick help thread



  • I searched and didn't found anything.
    so this thread is meant to post quick questions that don't justify a thread on it's own.

    i'll start. i have been tasked to create a simple asp.net core API. it has to read from a mongoDB(well, actually is a CosmosDB db, but the interface is the same as mongo)

    I'm having trouble trying to convert a Null BsonDocument into JSON.
    the code:

    [HttpGet("{id:length(24)}")]
            public string Get(string id)
            {
                var doc = _dal.GetInstrument(id);
                return doc.ToJson(_jsonSettings);
            }
    

    so, if the id is in the collection, GetInstrument handles me a BsonDocument and everything goes dandy.
    if it isn't. i get a BsonDocument (null) and the JSON parser goes boom:

    C# null values of type 'BsonDocument' cannot be serialized using a serializer of type 'BsonDocumentSerializer'.

    also, while i'm in it, how do i tell asp to return a 404 in that case?

    Thanks!



  • @jarry Sounds like one of the following approaches...

    a) Validate "doc" before calling ToJson().
    b) Proper exception handling/transformation to generate a 404....

    [or both]



  • @thecpuwizard yeah, i guess that should've been my question.

    i could make it so that calling GetInstrument throws an exception, and then catch it on the controller and make it return a 404. or validate it with something like

    if(doc is null){
     return 404
    }
    

    since i'm new in this ASP thing, which is the best/common way to handle this case?(IE i get a GET request for a resource that doesn't exist)



  • @jarry If you're extending ApiController you get a bunch of methods for different HTTP responses. E.g.

    public IHttpActionResult GetWhatever(int id)
    {
        // ... get your whatever
        if (whatever == null)
        {
            return NotFound();
        }
        else
        {
            return Ok(whatever);
        }
    }
    


  • @jarry said in The quick help thread:

    if(doc is null){

    We already know that doc is not null [otherwise you would get a NullReferenceException when calling .ToJSon(...).

    For a "pro-active" approach you need to look as what aspects (properties) of the object contain values (or null) that influence the behavior of .ToJson(...)



  • @thecpuwizard lazy typing on my part, when i said null, i meant BsonValue.Null which can't be serialized and hence my problem. i think i'll follow the route @hungrier proposed until i get a more robust understanding of ASP.NET


  • And then the murders began.

    Is there a T-SQL function akin to ISNULL() that will instead be based on whether or not the column exists?

    (Trying to run a query across many very-similar-but-not-identical databases. If a database is missing, say, the email column on a table, I want it to just return null instead of bombing the query.)



  • @unperverted-vixen said in The quick help thread:

    Is there a T-SQL function akin to ISNULL() that will instead be based on whether or not the column exists?

    NO... Two common alternatives:

    1. Check Schema and then dynamic SQL
    2. Check Schema then select from list of possible SQL implementation


  • @unperverted-vixen said in The quick help thread:

    Is there a T-SQL function akin to ISNULL() that will instead be based on whether or not the column exists?

    If T-SQL is anything like the other databases I've worked with, there's usually some system table that contains the definitions of tables or columns or whatever.


  • And then the murders began.

    @ben_lubar said in The quick help thread:

    If T-SQL is anything like the other databases I've worked with, there's usually some system table that contains the definitions of tables or columns or whatever.

    It does, but I was hoping for something simpler. If I check the schema, then to use the results I'm left with @TheCPUWizard's two options (dynamic SQL, or somehow picking between implementations in the query).

    Maybe I could (ab)use CASE to do it, which would at least let the number of branches be linear instead of a hydra of IF/ELSE statements, but that's still a lot more verbose than I was hoping for.


  • Impossible Mission Players - A

    @unperverted-vixen

    CASE WHEN COL_LENGTH('dbo.MyTable', 'myColumn') IS NOT NULL THEN myColumn
         ELSE NULL
    END
    

    This might work? It definitely is allowable for IF control flow...

    An alternate version that might be less finicky...

    CASE WHEN EXISTS 
                    ( SELECT 1 FROM sys.columns WHERE Name = N'myColumn' AND Object_ID = ObjectID(N'dbo.MyTable') ) 
         THEN myColumn
         ELSE NULL
    END
    


  • @izzion said in The quick help thread:

    @unperverted-vixen

    CASE WHEN COL_LENGTH('dbo.MyTable', 'myColumn') IS NOT NULL THEN myColumn
         ELSE NULL
    END
    

    This might work? It definitely is allowable for IF control flow...

    An alternate version that might be less finicky...

    CASE WHEN EXISTS 
                    ( SELECT 1 FROM sys.columns WHERE Name = N'myColumn' AND Object_ID = ObjectID(N'dbo.MyTable') ) 
         THEN myColumn
         ELSE NULL
    END
    

    That probably won't parse if myColumn does not exist.


  • Impossible Mission Players - A

    @pleegwat
    Yeah, I wasn't sure, I was spitballing from mobile before bed. And I forgot to come back and test it in the morning, so let's go do that now...

    Yeah, those don't parse with a missing column name, so I got nothing :man_shrugging:



  • @unperverted-vixen said in The quick help thread:

    Maybe I could (ab)use CASE to do it, which would at least let the number of branches be linear instead of a hydra of IF/ELSE statements, but that's still a lot more verbose than I was hoping for.

    How much DB access do you have?

    You could hook your code to a View or a Stored Procedure with a known-unchanging schema.


  • And then the murders began.

    @blakeyrat I have access but not ownership. I'd rather go with a more verbose approach than drop stuff in other peoples' DBs.



Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.