Simple serialize of encoding

My problem was the serialize of the Encoding . Let’s suppose that we have a class that have a property Encoding( maybe to read a file ).


internal class MyTest
{
    public MyTest()
    {
        enc = ASCIIEncoding.ASCII;
    }
    public Encoding enc { get; set; }
}


We want to serialize this class in order to let the administrator/people to decide what will be the encoding.

When we serialize( obvious, with NewtonSoftJson) , we obtain this kind of data:

{
“enc”: {
“IsSingleByte”: true,
“BodyName”: “us-ascii”,
“EncodingName”: “US-ASCII”,
“HeaderName”: “us-ascii”,
WebName“: “us-ascii”,
“WindowsCodePage”: 1252,
“IsBrowserDisplay”: false,
“IsBrowserSave”: false,
“IsMailNewsDisplay”: true,
“IsMailNewsSave”: true,
“EncoderFallback”: {
“DefaultString”: “?”,
“MaxCharCount”: 1
},
“DecoderFallback”: {
“DefaultString”: “?”,
“MaxCharCount”: 1
},
“IsReadOnly”: true,
“CodePage”: 20127
}
}

This is too much for someone to edit . We want a simple string that can be edited easy – and the WebName ,  that is , in fact , a string from https://www.iana.org/assignments/character-sets/character-sets.xhtml seems the obvious choice.

So –  I have done a JSONConverter class just for this property. It is very simple:

public class JsonEncodingConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (typeof(Encoding).IsAssignableFrom(objectType));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        string webName = "";
        if (reader.TokenType == JsonToken.String)
        {

            webName = reader.Value?.ToString();
        }
        existingValue = Encoding.GetEncoding(webName);

        return existingValue;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        string webName = (value as Encoding).WebName;
        serializer.Serialize(writer, webName);
    }
}

And can be used very easy:

MyTest m = new MyTest();
JsonEncodingConverter[] conv = new[] { new JsonEncodingConverter() };
string original = JsonConvert.SerializeObject(m, Formatting.Indented);
string data = JsonConvert.SerializeObject(m, Formatting.Indented, conv);
//https://www.iana.org/assignments/character-sets/character-sets.xhtml
Console.WriteLine(data);
Console.WriteLine("and now the original");
Console.WriteLine(original);
MyTest s = JsonConvert.DeserializeObject<MyTest>(data, conv);
Console.WriteLine(s.enc.WebName);

The result of serializing it is now

{
“enc”: “us-ascii”
}

And because it has this code

public override bool CanConvert(Type objectType)
{
    return (typeof(Encoding).IsAssignableFrom(objectType));
}

it means it will serialize just the encoding, not other tools.

And it is more easy to be edited by someone.

Moral: Aim for simple string that can be edited can be achieved when serializing. Do not stay with defaults!

 

( you can easy achieve backwards compatibility for already serialized Encoding by asking

if (reader.TokenType == JsonToken.StartObject)
{
    webName = reader.Value?.ToString();
    //handling old data format for encoding
    while (reader.TokenType != JsonToken.EndObject)
    {
        if (!reader.Read())
            break;
        if (reader.TokenType != JsonToken.PropertyName)
            continue;
        var val = reader.Value?.ToString();
        if (string.Compare("webname", val, StringComparison.InvariantCultureIgnoreCase) == 0)
        {
            webName = reader.ReadAsString();
            //do not break - advance reading to the end
            //break;
        }
    }

}

)

You should learn a framework–advice to starting programmers

There are many posts about getting to learn programming. And, of course, all starts with the simple instructions: + , –, % … Then things get somehow more complicated learning modular programming ( or functional, if you do not use global variables …)

After this, you start learning about classes and instances ( Plato is the master here) and overriding and deriving … And maybe some Design Patterns( please, do not talk about Singleton…)

Maybe you learn a bit about Sql( Tables and Views and StoredProcedures) and NoSql …

And after that, you have the basics to write code in any kind of language . But, when you want to start a new application

  1. How you start it  ?
  2. What are the deliverables ?
  3. How to make the Graphical User Interface ?
  4. How to make components ?
  5. and so on …

That’s what a  framework brings to the table: a clear way /  path to do applications. In my case I am talking about .NET Core / C# n(Console applications, Web Applications, Forms application ) . Also, you may want to separate Front End from Backend – Angular or Vue or … could help with that ( and .NET remains just an WebAPI layer) . A framyework ( or 2  – Front End and BackEnd) will teach you how to make possible an application without hassle.

Yes, it is true that the framework is constraining a lot- you do things the framework way, not your way . So what ? You want to get your first application done. The framework is showing you the path – you can walk under it. And you know that, if you do not walk the path, then “hic sunt leones” . You know also that the framework protect you from the problems.

So my advice to young programmers: Learn a framework . Then you could do your first application. And the second. Then you could you start questioning some of the decision of the framework that might not suit your application.

[PostEvent] HackTalks 2019

I have been a presenter and participant at #HackTalks Timisoara. I have seen lots of interesting people that do great stuff. Also lots of programmers interested of how to do better programming. It is a good vibe and lots of knowledge sharing.

As a participant , I can mention:

https://www.facebook.com/hacktalks.ro/posts/823295824708035 : Container Orchestration in the cloud for oncology  – data science and programming together for the greater good

https://www.facebook.com/hacktalks.ro/posts/821329954904622 : Platform revolution in mobility –  very informative and opinionated

 

https://www.facebook.com/hacktalks.ro/posts/820025591701725 : How to #model and #visualize complex conditional logic using a graph that describes a finite state machine in a highly flexible and data-driven way – nice way in JavaScript to describe logic flow with data .

 

My presentation was about Angular and .NET Core Everywhere and you can find the source code at https://github.com/ignatandrei/AngNetCoreDemo

Obtaining list of videos from a youtube playlist with Stankins

Because Stankins has a parser to html, you can have this kind of macro

#see all href

Stankins.HTML.ReceiverHtmlAHref file=https://www.youtube.com/playlist?list=PL4aSKgR4yk4OnmJW6PlBuDOXdYk6zTGps

#retain href column
StankinsObjects.FilterRetainColumnDataContains namecolumn=href stringToHave=PL4aSKgR4yk4OnmJW6PlBuDOXdYk6zTGps

#retain just videos which title contains 5Min

StankinsObjects.FilterRetainColumnDataContains namecolumn=a_text stringToHave=5Min

#remove column a_html

StankinsObjects.FilterRemoveColumn namecolumn=a_html

#transform column to li a href

StankinsObjects.TransformerAddColumnExpressionByTable expression=”‘<li><a href=’+ href+’>’ + a_text+'</a></li>'” newcolumnname=test nametable=TableLinks

#remove column href

StankinsObjects.FilterRemoveColumn namecolumn=href

#remove column a_text

StankinsObjects.FilterRemoveColumn namecolumn=a_text

 

The demo is at

https://azurestankins.azurewebsites.net/recipe/youtubeplaylist

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.