Technolog

Blogging over technologie.
Welcome to Technolog Sign in | Join | Help

Front Page News

  • Finally OData 7.x supports and ASP.NET Core 2.x

    Finally we can create OData (v4) services using ASP.NET Core.

    My first impression, it’s ok, plus it has extra features.

    Use my startup project, on Github as a sample. (It’s tricky to forget to enable features like Filter, otherwise you’ll and up with :

    value":"The query specified in the URI is not valid. The property 'Id' cannot be used in the $filter query option."}

    So, this is the Configure section

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
           {
               if (env.IsDevelopment())
               {
                   app.UseDeveloperExceptionPage();
               }
               var builder = new ODataConventionModelBuilder(app.ApplicationServices);
               builder.EntitySet<Car>("Cars");
          
               app.UseMvc(routeBuilder =>
               {
                   routeBuilder.Count().Filter().OrderBy().Select().MaxTop(null).Expand();
                   routeBuilder.MapODataServiceRoute("ODataRoute", "odata", builder.GetEdmModel());
                   // Work-around for #1175

                   routeBuilder.EnableDependencyInjection();
               } ) ;
           }

    To get PATCH and POST working, we need the [FromBody] Attribute like here

    public async Task<IActionResult> Post([FromBody] Car newCar)

     

    The sample, is downloadable here (ASP.NET-Core-With-Odata-7)

    01-16-2018, 21:31 by eprogrammer to Egbert Nierop technolog
    Filed under: , ,
  • Howto open ("/dev/urandom") on Windows

    Just copy-paste might save you some time. rand_s is pretty safe on Windows since it uses RtlGenRandom(), but you’ll have to define _CRT_RAND_S first before <stdlib.h>

    Assuming that the cpp somewhere in the class has: m_fd = open("/dev/urandom", O_RDONLY);

    Original code: (thanks jacketzhong)

    sds CRedLock::GetUniqueLockId()

    {

    unsigned char buffer[20];

    if (_read(m_fd, buffer, sizeof(buffer)) == sizeof(buffer)) {

    //获取20byte的随机数据

    sds s; s = sdsempty();

    for (int i = 0; i < 20; i++)

    {

    s = sdscatprintf(s, "%02X", bufferIdea); } return s;

    }

    else

    {

    //读取失败 printf("Error: GetUniqueLockId %d\n", __LINE__); }

    return NULL;

    }

    Windows CPP compatible:

    note: rand_s is not an ANSI standard.

    sds CRedLock::GetUniqueLockId()
    {
        //获取20byte的随机数据
        auto retVal = sdsempty();
        auto max = 20 / sizeof(unsigned int);
        for (int i = 0; i < max; i++)
        {
            unsigned int number;
            if (rand_s(&number) == 0)
            {           
                retVal = sdscatprintf(retVal, "%08X", number);           
            }
        }
        return retVal;
    }

    11-06-2017, 10:57 by eprogrammer to Egbert Nierop technolog
  • Howto get the ASP.NET Core ContentRoot path?

     

    There are 3 ways that I have found to be working within Startup.cs

    1. use Environment variables.  This however, only works if you also have added the environmentvariables. (builder.AddEnvironmentVariables(); )
    2. var env = Configuration.GetSection("ASPNETCORE_CONTENTROOT");
      var path =     env.Value

    3. Resolve IHostingEnvironment from Services.
        var sv = (IHostingEnvironment)services.FirstOrDefault(f => f.ServiceType == typeof(IHostingEnvironment)).ImplementationInstance;
      var path = sv.ContentRootPath;
      Though, I can imagine you would rather resolve HostingEnvironment but this does not work during ConfigureServices scope..
    4. Use Directory
      eg:  var path = Directory.GetCurrentDirectory();
    09-10-2017, 20:06 by eprogrammer to Egbert Nierop technolog
  • ASP.NET Core MVC. Howto set Casing strategy for JSON

    While converting a previous piece of code, written using Mvc 4.x I found that the output of the Json previously, when set no option, was unchanged, so a class with a property say, Name would output in JSON as ‘Name’.

    However, ASP.NET Core Mvc
    when returning JSon results, it now defaults to camelCasing.

     

    My output had to be:

    {
        "page": 1,
        "records": 2,
        "rows": [
            {
                "Id": 2,
                "Name": "asdfasdf",
                "UrlSlug": "asdfasdf",
                "Description": "asdf"
            },
            {
                "Id": 1,
                "Name": "Bkaat",
                "UrlSlug": "Blaat",
                "Description": "zdf
    asdfasdf asdf a"
            }
        ],
        "total": 1
    }

    but it was camelCased.

     

    So, HOW to set this to the previous behavior (its old software, so I won’t change everything)

    Simple like this:

    public void ConfigureServices(IServiceCollection services)

    {

        services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver() { NamingStrategy = new DefaultNamingStrategy()});

     

    And finding further options, you also can set it to SnakeCaseNamingStrategy (this is like ‘url_slug’ etc)

    And of course, CamelCaseNamingStrategy, which is the default.

    I hope this saves you some time, and you don’t need to implement a custom contract resolver.

    09-10-2017, 14:13 by eprogrammer to Egbert Nierop technolog
    Filed under: ,
  • Give your C# class Initializer support

    Would you like a to boost your class which hosts a collection, and utilize a cool C# language feature, which is collection initializer support?

    For instance var myList = new List<int>() {1,3,4} where {1,3,4} is the initializer.

    The basic idea is to implement IEnumerable<T>, and IEnumerator<T> and the class must have an ‘Add’ method with the correct signature.

    I made the class generic so you can initialize any array (ok, not for structs and simple types, but you modify a few things and that works too)

    // our sample class for iteration feeding

    public class Address
       {
           public string Street { get; set; }
           public string StreetNumber { get; set; }
           public string ZipCode { get; set; }
           public string City { get; set; }
       }
       public static class Program
       {
           static void Main()
           {
               var t = new ClassWithInitializerSupport<Address> {
                   new Address()
                   {
                       Street = "Mainstr.",
                       StreetNumber = "1",
                       City ="London"
                   },
                  new Address()
                   {
                       Street = "De Dam",
                       StreetNumber = "1",
                       City ="Amsterdam"
                   },
                   new Address()
                   {
                       Street = "Mangostreet",
                       StreetNumber = "123",
                       City ="New York"
                   }
               };
               foreach(var a in t)
               {
                   Console.WriteLine("Street {0}, City {1}", a.Street, a.City);
               }

    }

    public class ClassWithInitializerSupport<T> : IEnumerable<T>, IEnumerator<T> where T : class
       {
           public ClassWithInitializerSupport()
           {
               arr = (T[])Array.CreateInstance(typeof(T), 0);
               pos = -1;
           }
           private T[] arr;
           private int pos;
           public T Current => arr[pos];

           object IEnumerator.Current => arr[pos];

           public void Dispose()
           {

           }

           public IEnumerator<T> GetEnumerator()
           {
               return this;
           }
           public void Add(T v)
           {
               var p = arr.Length;
               Array.Resize(ref arr, p + 1);
               arr[p] = v;
           }
           public bool MoveNext()
           {
               if (pos + 1 < arr.Length)
               {
                   pos++;
                   return true;
               }
               return false;
           }

           public void Reset()
           {
               pos = -1;
           }

           IEnumerator IEnumerable.GetEnumerator()
           {
               return this;
           }
       }

    05-20-2017, 1:03 by eprogrammer to Egbert Nierop technolog

Recent Additions

  • None
Powered by Community Server, by Telligent Systems