Technolog

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

Front Page News

  • PowerShell script to upload a file to a remote FTP server

    I needed a simple script to upload a file remotely to an FTP server, and found a script on StackOverflow.

    However, the script could use some improvements such as SSL. Here it is. Good luck with it

    $ftp = [System.Net.WebRequest]::Create("ftp://ftp.yourserverblahblah.com/public/" + $args[0])
    $ftp = [System.Net.FtpWebRequest]$ftp #cast
    $ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile #"STOR"
    $ftp.Credentials = new-object System.Net.NetworkCredential("someuser","incrediblepassword****")
    $ftp.UseBinary = $true
    $ftp.UsePassive = $true
    $ftp.EnableSsl = $true

    $fullPathIncFileName = $MyInvocation.MyCommand.Definition

    $currentExecutingPath = [System.IO.Path]::GetDirectoryName($fullPathIncFileName)
    $file = [System.IO.Path]::Combine($currentExecutingPath, $args[0])
    Write-Host "Going To Copy " + $file
    # read in the file as a stream.
    $content = [System.IO.File]::OpenRead($file)

    # get the request stream, and copy the bytes into it
    $rs = $ftp.GetRequestStream()
    $content.CopyTo($rs)
    $rs.Close()
    $content.Close()

    08-05-2018, 15:28 by eprogrammer to Egbert Nierop technolog
  • An easy Taghelper to make an element ‘active’ when clicked using Razor.

    Still using backend HTML logic.

    ASP.NET Core makes things a lot more easier for us, backend developers. Though, accent today, is more on frontend development, still, for reasons of security for instance, backend state management is still used.

    Now take a look at this tiny gem, a TagHelper.

    A ‘which menu has been clicked-set-active-helper’

    What it does, basically, is checking if a <li> element has an attribute activecheck. If so, it detects which ‘action-route’ was executed/is executing and if the name matches, it adds class=”active”. So the output will be  e.g.
    <li class=”active”><a href=”/”>Home</a></li>

    e.g. in the Razor View I have:

    <ul class="rd-navbar-nav">
                                         <li activecheck="true" data-menu="Index" >
                                              <a asp-controller="Home" asp-action="Index">Home</a>
                                          </li>

    I had to add a ‘data-menu’ attribute, because Taghelpers, can not, as far as I found, parse the raw Razor Markup, when using ‘GetChildContentAsync()’  for instance, it only gets the HTML output that’s already there, without Razor markup. So, I cannot parse the child anchor and retrieve asp-acction=”Index”.
    Therefore, I specify it again using data-menu=”Index”. Note, this is removed later by the taghelper.

    using Microsoft.AspNetCore.Html;
    using Microsoft.AspNetCore.Mvc.Controllers;
    using Microsoft.AspNetCore.Mvc.Infrastructure;
    using Microsoft.AspNetCore.Razor.TagHelpers;

    namespace ladidah.TagHelpers
    {
        [HtmlTargetElement("li", Attributes = "activecheck")]
        public class LiActiveHelper: TagHelper
        {
            public bool activecheck { get; set; }
            private readonly string menu;
            public LiActiveHelper(IActionContextAccessor httpContext)
            {
                var currentRoute = (ControllerActionDescriptor)httpContext.ActionContext.ActionDescriptor;
                menu = currentRoute.ActionName;
            }
            public override void Process(TagHelperContext context, TagHelperOutput output)
            {
                if (activecheck)
                {
                    var dataMenu = output.Attributes["data-menu"];
                 
                     if (dataMenu != null && dataMenu.Value is HtmlString str && str.Value == menu)
                    {
                        output.Attributes.RemoveAll("activecheck");
                        output.Attributes.RemoveAll("data-menu");
                        if (!output.Attributes.ContainsName("class"))
                        {
                            output.Attributes.SetAttribute("class", "active");
                        }
                    }               
                }          
            }
        }
    }

    To activate this taghelper, I had to add the following line in my _ViewImports.cshtml file

    @addTagHelper ladidah.TagHelpers.LiActiveHelper, ladidah

    Benefit of IoC in ASP.NET Core.

    In my ConfigureServices method, in startup.cs I had to add the following line, in order to be able to get the action context of the current MVC Controller.

    public void ConfigureServices(IServiceCollection services)
           {

    // code removed for readability

      services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

    }

    I hope you find this snippet useful.

    04-19-2018, 13:37 by eprogrammer to Egbert Nierop technolog
    Filed under: ,
  • 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

Recent Additions

  • None
Powered by Community Server, by Telligent Systems