Adding Dropdown Arrow for Chosen Plugin in Multiselect Mode

April 2, 2017

I use the jQuery Chosen plugin in a web application, and recently got the request to display a dropdown arrow in multiselect mode.

I found an answer on SO regarding styling of the dropdown arrow, but that covered only singleselect mode. At least a starting point 😉

Within minutes, I had a CSS-only solution for this particular problem:

<style type="text/css">
.chosen-container-multi.chosen-container .chosen-choices::after {
    background: url(@Url.Content("~/Content/chosen-sprite.png")) no-repeat 3px 4px;
    width: 16px;
    height: 100%;
    content: " ";
    position: absolute;
    right: 0;
    background-color: lightgray;
}
</style>

(Note that this is an ASP.Net MVC application, and @Url.Content() computes the URL relative to application root.)

Only after I solved this, I found that there is a closed (and unresolved) issue on github from 2011, with comments up to 2016, but no solution to a valid feature request…


Emoticon Selection in ASP.Net MVC

March 30, 2017

I had to implement a good/bad/neutral selection UI in an ASP.Net MVC application.

This simple task turned out to be rather cumbersome, given different browsers implementing different things differently, and the MVC framework restricting access to generated markup.

I first thought about a DropDownList (i.e.) rendering a set of emoji, only to find

  • you cannot pass a C# emoji as SelectListItem.Text
new SelectListItem {Text = "\u1F60A" }
  • you cannot add the emoji HTML entity 😊 astext (at least not in Chrome)
  • you cannot add a @class parameter to SelectListItem
  • you cannot add a background-image:url() definition to an
  • you cannot add HTML tags inside an(

    )

However, I found code to overcome the limitations of SelectListItem, either by copying and extending code from the MS MVC framework, or by XML manipulation of the built-in HTML generator.

Maybe the dropdown list was just the wrong path to follow, so I searched for ways to style radiobuttons, and found this nice demo on codepen.

I modified the demo to fit my needs, and voilà, here’s my first codepen:

A radiobutton-based emoji selector

Update: Apparently, IE does not render an <img> inside a <label> clickable, unless you specify pointer-events: none.


Online Tools Collection

March 23, 2017

Encoding / Decoding

Base64 Decode and Encode – Encode text to base64, decode base64 to text

utf8-decoder – Decode bytes and characters to Unicode character names

HTML entity encoder/decoder – Translate text into HTML entities

Punycoder – Punycode (IDN) converter

Unicode code converter – Convert Unicode text to code point values (hex, UTF-8, etc.)

Images

Favicon Generator – Create favicons from image

ICO Convert – Convert image to .ico format

Palettes and Gradients

Ultimate CSS Gradient Generator – Gradient with 2 or more colors, generates CSS including support for older browsers

CSSmatic – Gradient generator

Paletton Color Scheme Designer – generate palette with up to 4 colors from base color

Parsing

.Net Regex Tester

Online Collaboration

EtherCalc – spreadsheet


Using PowerShell to find IIS Sites without https enabled

March 21, 2017

To retrieve all certificates registered in IIS, run this command in PowerShell Administrator mode (source)

import-module WebAdministration
get-childitem iis:SslBindings

To retrieve the bindings (i.e. http and https properties) of IIS sites, run (source)

import-module WebAdministration
get-website | select name,id,state, physicalpath,
@{n="Bindings"; e= { ($_.bindings | select -expa collection) -join ';' }}

I used the last code snippet to find the IIS sites without https / SSL certificate:

import-module WebAdministration 
get-website | where {$_.State -eq "Started"} | 
select name, 
  @{n="Bindings"; e= { ($_.bindings | select -expa collection) -join ';' }} | 
where {$_.Bindings -notmatch "ssl" } 

There is also a nice script finding IIS certificates and whether they are used in an IIS site or not.


Adding SSL Wildcard Certificates to IIS Webs

March 21, 2017

As web browsers start to issue warnings on plain http websites if you are asked to input username/password, it’s time to add SSL certificates even on dev/test servers. We can expect more aggressive warnings in the future 😉

Apparently there is a way to create a self-signed certificate built into IIS (screenshot from Windows Server 2008)

iis create certificate

but this seems to create cerficates only for the host name, not for any domain hosted on the machine.

Back to square one, start up a current Linux machine, and make sure your openssl is newer than version 1.0.1f. (Remember Heartbeed?).

The instructions I found to create self-signed certificates are nearly identical (source, source, source)

openssl genrsa 2048 > my-host.key
openssl req -new -x509 -nodes -sha1 -days 3650 -key my-host.key > my-host.cert
# make sure Common Name starts with "*.", e.g. *.my-host.com
openssl x509 -noout -fingerprint -text < my-host.cert > my-host.info
cat my-host.cert my-host.key > my-host.pem

For use in IIS, you need to create a .pfx from these certificate files:

openssl pkcs12 -inkey my-host.pem -in my-host.cert -export -out my-host.pfx

Copy the .pfx to your IIS machine.

In IIS Manager, select “Server Certificates” on the server node, click “Import…” to import the .pfx certificate.

Start up mmc, “File”, “Add/Remove Snap-in”, select “Certificates”, “Add”, “Computer account”, “Finish”, “OK”, (this click orgy shows you how important certificates were in 2008, as compared to Start/Administrative Tools/Data Sources (ODBC) 😉 ) and find the imported certificate(s) under

Console Root\Certificates\Personal\Certificates

Right-click each of them, select Properties, and make sure that the Friendly Name starts with “*.” for wild-card certificates. Otherwise, you cannot assign a host name for https web sites.

Back in IIS Manager, select each site you want to add https support, click Bindings, Add, select Type: https and select the wild-card SSL certificate. Only if the friendly name starts with *, you can/must set the site’s Host name. Click OK and you are done.

If you want your sites to redirect http to https automatically, make sure the Require SSL box is not checked in the site’s SSL Settings.

The minimal web.config to perform these redirects looks like this (source, source)

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Redirect-HTTP-HTTPS-IIS">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="^OFF$" ignoreCase="true" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" 
            redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

Be aware that while these steps enable https for your IIS sites, self-signed certificates still require the users to explicitly accept the certificates in their browsers, which will raise an “Unknown issuer” warning at their first visit.

Update: There also seems to be a Powershell way to do it 😉


Installing AWStats on Windows Server 2012

March 7, 2017

To install AWStats on Windows, first download the current version from awstats.org. If you don’t have Perl on your machine, get Strawberry Perl for Windows, as ActivePerl requires an annual Business License for production use.

On the server, create a web directory and a data directory for awstats. Follow the steps in the AWStats Setup Guide.

To access the log files of a remote IIS, I created a read-only share on c:\inetpub\LogFiles, and had to run

icacls c:\inetpub\LogFiles /reset /t

to allow non-admin access to the IIS log files.

To get Strawberry Perl to run on IIS, follow this Installation Guide:

  • In the Web Server role, you need to have the CGI feature installed.
  • In IIS Administrator, create a web site or application hosting AWStats. In the site or application, you need to add a Script Map for *.pl executing
C:\path\to\perl.exe "%s" %s

Things should be running by now if you browse to

http://myHost/awstats/cgi-bin/awstats.pl?config=mySite

I noticed that the stats only included data from the installation date (IIS logs are configured to daily log files).

Answers on the internetz suggest to merge old log files using logresolvemerg.pl, a script that ships with awstats.

C:\awstats\tools>perl logresolvemerge.pl [all my log files] > merged.log

Replace the LogFile entry in your config file(s) to point to the merged log file

LogFile="C:\awstats-data\merged.log"
#LogFile="\\path\to\LogFiles\W3SVC1\u_ex%YY-1%MM-1%DD-1.log"

and run

perl awstats.pl -config=mySite

again after deleting the previously generated data files.

Unfortunately, the merged log only resulted in “dropped” and “corrupted” records:

Phase 1 : First bypass old records, searching new record...
Searching new records from beginning of log file...
Jumped lines in file: 0
Parsed lines in file: 30376
Found 16100 dropped records,
Found 0 comments,
Found 0 blank records,
Found 14276 corrupted records,
Found 0 old records,
Found 0 new qualified records.

This may be caused by a number of reasons, but it turned out that the merged log requires a specific LogFormat:

LogFormat="%time2 %other %method %url %query %other %logname %host %ua %code %other %other %other"

Finally, I created a batch file awstats.cmd to update all my statistics

net use z: \\host\LogFiles awstats /user:awstats
d:
cd D:\wwwroot\awstats\wwwroot\cgi-bin
perl awstats.pl -update -config=mySite1
perl awstats.pl -update -config=mySite2
...
net use z: /delete

and created a scheduled task to automatically execute the script every day.


Handling the “Size Limit” in AD Queries

February 10, 2017

I created a small tool to mirror AD data into an SQL Server database. The AD queries essentially looked like this

var conn = new ADODB.Connection();
conn.Open("Provider=ADsDSOObject", "", "", 0);

const string where = "objectCategory='group' ";      

var qry = string.Format(@"SELECT objectCategory, displayName, [more attributes]
FROM 'LDAP://{0}/{1}' 
WHERE {2}", server, start, where);

object recs;
var rs = conn.Execute(qry, out recs, 0);

for (; !rs.EOF; rs.MoveNext())
{
    // ... process record
}

The attributes available in AD have been taken from here.

The code worked fine for many months, until one day it threw an exception:

System.Runtime.InteropServices.COMException (0x80072023): The size limit for this request was exceeded.
at ADODB.RecordsetClass.MoveNext()

It turned out that the query result suddenly exceeded 3000 records, which may or may not be a magic or configurable limit of fetches for a single AD query – probably also including the number of records each fetch returns. Who knows.

Thanks goes to the internetz, which provided me with a solution which now fetches more than 3000 records. Just replace the conn.Execute() part with

var cmd = new ADODB.Command {ActiveConnection = conn, CommandText = qry};
cmd.Properties["Page Size"].Value = 10000;
cmd.Properties["Timeout"].Value = 30;
cmd.Properties["Cache Results"].Value = false;