2017-10-04

Webpack has been initialised using a configuration object that does not match the API schema.

On Windows, when running yarn (custom action "start") to start the dev server, on the step that starts the webpack-dev-server, I had the following error message:

$ webpack-dev-server --debug --hot --progress --colors
 10% building modules 2/2 modules 0 active
 Invalid configuration object. 
 Webpack has been initialised using a configuration object that does not match the API schema.
 ... 

This was not an easy one to understand, but it turned out to be very simple.

When I had CD-ed into the React app folder, I had typed the foldername with only lower case characters. The foldername was originally typed with a capital first letter. Webpack did not like that.

Solution:
cd ..
cd Folder
yarn start


2017-09-11

Adding nicer icons to the PageTree in EPiServer

I did some research about adding nicer icons for pages in the EPiServer Page Tree, and I came up with some nice resources.

What seems to be common for all approaches is that you must create css-classes that encapsule each icon to use. At the moment I don't see how to get around this without actually creating the classes.

You also need to create an InitializableModule which sets up the icons when the web is started. I have omitted that code here. Please read the example from the first example below (from blog.nansen.com), for that code.

This example is complete and shows how to use your own (or a third party lib) icons:
http://blog.nansen.com/2014/10/page-tree-icons-in-episerver-cms-75.html

This example shows how to create your own icons (as an image sprite) and use for the icons: https://jonika.nu/JonasBlogg/archives/347


Here's one that shows how to use the already included icons from EPiServer:
https://ericceric.ghost.io/use-episervers-content-icons-as-site-tree-icons/

In stead of creating and maintaining the list of Episerver icons yourself, as in the example above, you could go for the Jon D Jones nuget package: https://www.nuget.org/packages/JonDJones.IconPack/. This iconpack does not really contain any icons, just convenience constants that point to the built-in episerver icons (it seems so to me anyway).


I created a generic attribute, based on reflection, that plugs in the JonDJones icon pack (download from Nuget, as mentioned) into the first example I mentioned from the "nansenblog":

[AttributeUsage(AttributeTargets.Class)]
public class ContentIconAttribute : Attribute
{
    public ContentIconAttribute(Type type, string propertyName)
    {
        IconClass = GetStaticStringValueFromLib(type, propertyName);
    }

    private string GetStaticStringValueFromLib(Type libType, string name)
    {
        var fieldInfo = libType.GetField(name);
        var propInfo = libType.GetProperty(name);
        var value = (fieldInfo?.GetValue(null) ?? propInfo?.GetValue(null)) as string;
        return value;
    }

    /// 
    /// Css class to apply to the icon
    /// 
    public string IconClass { get; set; }
}

And here's how to use it:
using JonDJones.IconPack;

[ContentIcon(typeof(ObjectIcons), nameof(ObjectIcons.Start))]
public class StartPageModel : BasePage
{
    ...
}

2017-06-13

Always run Visual Studio as administrator

I am using Visual Studio a lot, and when I pin it to the task bar in Windows 10, right-clicking it will bring up a (popup) list of my last opened projects.

I need to run VS as Administrator, to be able to debug my web applications running on the local IIS.

So when I right-click the pinned VS-icon on the task bar, I can right-click on Visual Studio, then select "Run As Administrator", which is fine. The problem is that I cannot right-click on any of my previously opened solutions and run VS as admin while opening that solution.

On a shortcut (and probably also some exe-files) you will get the option to "always run as administrator". Problem is, this option does not appear when looking at the properties of the DevEnv.exe file, so you need to "fake" it by going into the compatibility settings.

In essense: What I want to do is basically to always open Visual Studio "As Administrator".

So here's how:

From link 1 below:
  1. Locate devenv.exe, by right-clicking the VS icon and selecting properties, then see the link in the shortcut.
  2. Right-click devenv.exe and choose Troubleshoot compatibility
  3. In the new window click at Troubleshoot Program
  4. Check The program requires additional permissions
  5. Click "Next" until you get to a button that says "Test the application". 
  6. Click the button and VS will be launched "As Administrator". 
  7. Switch back to the dialog, press "Next".
  8. Click the top option to save the preferences.

Sources:
  1. https://superuser.com/questions/465065/no-compatibility-tab-for-devenv-exe-vs-2010-and-vs-2012-on-windows-8
Related:


2017-04-19

Get time for given country

This code gets the first time zone for a country (meaning it probably won't work if your country has more than one), and calculates the date/time given the UTC date/time.

The method is an extension to the DateTime type, meaning you can use it by typing .AsLocalTimeForGivenCountryFromUtc(countryCode) after a variable or function returning that type. The countryCode parameter is a string, and must be a two-letter ISO 3166-1 country code.

You need to import John Skeets NodaTime library from NuGet.

Code:
using NodaTime.TimeZones;
using System;
using System.Linq;

namespace MyNameSpace
{

    public static class DateTimeExtension
    {

        public static DateTime AsLocalTimeForGivenCountryFromUtc(this DateTime utcDateTime, string countryCode)
        {
            //no matter what tz info is on the date, assume it is UTC
            var dte = new DateTime(utcDateTime.Year, utcDateTime.Month, utcDateTime.Day, utcDateTime.Hour, utcDateTime.Minute, utcDateTime.Second, DateTimeKind.Utc);
            var tzMapping = TzdbDateTimeZoneSource.Default.WindowsMapping.MapZones.FirstOrDefault(t => t.Territory == countryCode); //NodaTime
            var tz = TimeZoneInfo.FindSystemTimeZoneById(tzMapping.WindowsId);
            return TimeZoneInfo.ConvertTimeFromUtc(dte, tz);
        }
    }
}

2017-04-06

Visual Studio 2015 Freezes when ReSharper is running

Ok, so finally got ReSharper installed. Again. Been doing fine without it for a while, but the team is using it so I got myself a license. But it was a bit of a disappointment at first. It seems that whenever I build my solution, which has both some C# and one F# project, VS freezes. Today it even crashed after being unresponsive for quite a few minutes. Seems more people have the same problem:

https://resharper-support.jetbrains.com/hc/en-us/articles/206546149-Visual-Studio-with-ReSharper-is-freezing-and-or-crashing?flash_digest=fcf1e14381f3c8171cbc9129d0fa536af24a7a10

So what happened was that I was in my F# project making some changes, then I built the solution, and then I went on to do some more changes in the same project, but things were moving very slowly, and in the end froze completely and then the crash.

So my working theory is that the problem may be related to F#. So I have added the F# project folder to the exclude list in R# options. I also added the *.fs file type to the excluded files.

So far it's looking good. I have built several times, and editing F# code is smooth.

PS. Still looking good! :) Think I found the solution!

PPS. Also disabling R# for TypeScript files may be a good idea (or so I've heard).

2017-04-03

Things that may be confusing when moving to F#

I have been doing C# for quite a few years, and I have started using F# recently. I am only occasionally coding in F# so I tend to forget some things from one time to the other. So here's what I must remember:
  • The sequence of F# code files in Visual Studio matters!
    • To have access to a module or type from another module, that module must be declared before (higher up) the other module.
    • To move a module up, use Alt + ArrowUp.
  •  Indentation matters!
    • If some code is part of some enclosing element, that code must be indented.
Here's a great article:
http://connelhooley.uk/blog/2017/04/10/f-sharp-guide

2017-01-13

Free Code Improvement Alternatives

I really liked using ReSharper (JetBrains) in Microsoft Visual Studio.

There are also some other commercial tools like it:
- CodeRush (DevExpress)
- JustCode (Telerik)

The functionality that I found most useful was:
- Go To Implementation
- Find Usages
- Suggestions on code improvements
- Extract function

I think that ReSharper has become too expensive now, currently at a $299 first year subscription, then a bit lower on subsequent years. That's about 40% of the price of Visual Studio Professional, and you don't even buy the product - you subscribe.

So I am testing out this combo as an alternative:

Roslyn provides the Light Bulb for code improvements:
https://blog.tommyparnell.com/vs-2015-getting-resharper-experiance-without-resharper/

Several very handy tools:
- Productivity Power Tools

For more code improvement suggestions (pick one, not both):
- CodeCracker for C# (testing this now, looks good)
- Refactoring Essentials for Visual Studio*

I have also tested CodeMaid, but not just right now*.
I may enable it again at a later point in time though.
It looks like a very useful addition to Visual Studio.

Here are some related Stack Overflow questions:
http://stackoverflow.com/questions/2834439/what-are-some-alternatives-to-resharper
http://stackoverflow.com/questions/24542406/alternatives-to-resharper

*Enabling too many competing plugins may cause VS to run very slowly.

2016-08-05

Appear to browse from a different country

If you want to test what your website looks like for people in a different country, you might like to try this:

http://teleport.to/

Use at your own discretion.

2016-06-02

CS1056: Unexpected character '$'

When you get the message " CS1056: Unexpected character '$' " in runtime asp.net, it means that the front end file (html/aspx) is using a way of formatting strings which is called "string interpolation".
But to use string interpolation in your web frontend files you must put the following into your web.config file:

<system.codedom>
  <compilers>
    <compiler language="c#;cs;csharp" extension=".cs"
      type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
      warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
    <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
      type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
      warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
  </compilers>
</system.codedom>

Source:
http://stackoverflow.com/questions/30832659/string-interpolation-in-a-razor-view
 
Disclaimer:
The above worked for me, but may not work for all .NET Framework versions and/or ASP.NET versions.

2016-03-02

Catching mails

When developing a solution, sometimes it is nice to be able to catch mails and store them somewhere in stead of potentially sending them to real customers.

In web.config or app.config, there is a setting that can accomplish that for you:

<system.net>
  <mailSettings>
    <smtp deliveryMethod="SpecifiedPickupDirectory">
      <specifiedPickupDirectory pickupDirectoryLocation="c:\Temp\Mail"/>
    </smtp>
  </mailSettings>
</system.net>
 If you install an eml-viewer or maybe just a regular mail client, you can open and read the mails from the folder you specified.

Source:
http://stackoverflow.com/questions/567765/how-can-i-save-an-email-instead-of-sending-when-using-smtpclient

2016-02-16

Fiddler on Windows 10

I've previously written about Fiddler here:
http://stgaup.blogspot.no/2013/03/fiddler-tricks.html

When installing Windows 10, you create an account which is not connected to any external host in any way. Later however, you probably associate your account/Windows 10 instance with your Microsoft account. Afterwards you will use your Microsoft account when logging in.

In my previous post I mentioned one could make Fiddler work by running the app pool on the same account at that on which Fiddler is running (and which you are most likely logged on to).

But there are now two accounts it seems:
  • the one you created while installing, 
  • and the Microsoft account,  
so which one should you use when running Fiddler?
Turns out it works with the Microsoft account.

Username: someone@hotmail.com/outlook.com/live.com etc.
Password: the password associated with the Microsoft account.

2016-02-12

DLL-hell: log4net... oldKey vs newKey

Since log4net now comes in 2 flavours, namely oldkey and newkey, since the Development team decided to change the key, this may cause some trouble.

Here's my solution:

1) Update your Project by getting the latest version from nuget (currently 1.2.15.0) by using update (or other). This should get you the "newkey" version, which has publicKeyToken="669e0ddf0bb1aa2a". You can also download it from Apache.

2) Go to Apache and download the oldkey version (publicKeyToken="1b44e1d426115821"), and place it somewhere nice on your DEV PC.

3) Open a Developer Command Prompt for your version of Visual Studio, and run the GACUTIL utility to install the oldKey dll into the Global Assembly Cache (GAC).

4) Update the Runtime/assemblyBinding section of your config file (web.config  or App.config) With the following:

<dependentAssembly>       
  <bindingRedirect oldVersion="0.0.0.0-1.2.15.0" newVersion="1.2.15.0" />       
  <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />     
</dependentAssembly>     

<dependentAssembly>
  <bindingRedirect oldVersion="1.0.0.0-1.2.15.0" newVersion="1.2.15.0" />
  <assemblyIdentity name="log4net" publicKeyToken="1b44e1d426115821" culture="neutral" />
</dependentAssembly>

Hope this helps!

The .NET SDK 4.0 or 4.5 tools could not be found.

First, my situation was that I had a brand new laptop which I had installed Windows 10 on. Next I installed Visual Studio 2015 Community Edition, full install (including support for F#).


So when I tried to compile my F# projects, I got this error:

The type provider 'Microsoft.FSharp.Data.TypeProviders.DesignTime.DataProviders' reported an error: The .NET SDK 4.0 or 4.5 tools could not be found.

So I found these resources:

The third one seems to be the one to read, it has several suggestions. I tried to do several of them, but what fixed it in the end for me was the suggestion in the very last post:
  • Install Windows 8 SDK.

I first had a problem installing it, it rolled back while installing, so what I think worked was to just check "Windows SDK" and ".NET 4.5 SDK" in the list of components, leaving the rest unchecked. I also tried to re-register the vbscript dll as per this post (which you may also try if it won't install):
  • http://stackoverflow.com/questions/19251176/error-code-2753-during-install

I also ran the script that was mentioned in the forum, just mentioning in case it may have been a part of the solution.


I also restarted my PC quite a few times.


 So what didn't work (or did not seem to):
  • Install Windows 8.1 SDK
  • Install Windows 10 SDK

2015-01-22

Fun with programming

Have a go at these puzzles:
https://www.codehunt.com/
http://www.pexforfun.com/

Here’s a fun programming language that even (or especially) kids may try:
https://blockly-games.appspot.com/

Here’s another called Scratch:
http://scratch.mit.edu/

Resources for teaching kids to code:
http://www.teachkidstoprogram.com/

2014-07-28

Windows 7 Won’t Boot: 0x0000007B

My Windows 7 PC would not boot. It turned out some of the boot files were corrupt or missing, and I got a bluescreen during startup:
https://flic.kr/p/odkE3W.

Also when I tried to fix the problem using automatic recovery I got an error saying “Failed to Save Startup Options”.

Luckily someone else had had the same problem:
http://answers.microsoft.com/en-us/windows/forum/windows_7-system/bootmgr-error-cant-load-windows-automatic-repair/e2f50f68-a49a-4936-8ca6-8d920557262a?rtAction=1406539673501

Solution summary:

1. Open the command prompt from the recovery console.

2. Run: BOOTREC C:\Windows C:

It will create new boot files on your C-drive. The first parameter is your windows folder.

3. If your boot sector is in fact damaged (mine was not) you should probably drill deeper into the Community answer mentioned above and follow the steps.

2014-04-28

System.ServiceModel.AddressAccessDeniedException: HTTP could not register URL

I run into this error message from time to time, and every time I have forgotten what to do, hence I am writing it here.

This is the command:
netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user

Source:
http://msdn.microsoft.com/en-us/library/ms733768.aspx

2014-02-06

EPiServer PageReference Extension: FindPagesOfType<T>(…)

Here’s my extension method for searching for pages of a given type T under an EPiSever (PageTypeBuilder) Page referred to by the PageReference which this method extends.

public static IEnumerable<T> FindPagesOfType<T>(
this PageReference pageLink, string languageBranch)
where T : TypedPageData
{
    //get page type id from type
    var pageTypeId = PageTypeResolver.Instance.GetPageTypeID(typeof(T));

    if (!pageTypeId.HasValue)
        return new List<T>(); //return empty enumerable

    // Create criteria collection
    var criterias = new PropertyCriteriaCollection
        {
            // Find pages of a specific page type                       
            new PropertyCriteria()
                {
                    Name = "PageTypeID",
                    Condition = CompareCondition.Equal,
                    Required = true,
                    Type = PropertyDataType.PageType,
                    Value =  pageTypeId.Value.ToString("0")
                }
        };

    var pages =
        DataFactory.Instance.FindPagesWithCriteria(
            pageLink,
            criterias,
            languageBranch,
            new LanguageSelector(languageBranch))
            .Cast<T>();

    return pages;
}

Example usage:

var myArticles =
PageReference.StartPage.FindPagesOfType<Article>(CurrentPage.LanguageBranch);

2014-01-28

Invalid User Control Reference added by ReSharper?

ReSharper usually offers nice autocomplete suggestions. However when on a WebForm, adding a WebUserControl and then clicking the autocomplete popup suggestion adds an usnusable Register statement. Here’s an example of such a statement:

<%@ Register TagPrefix="PRE" Namespace="My.Namespace" Assembly="My.Namespace" %>
What happens when this is added is that the compiler thinks everything is fine, but when you try to run it the controls inside your user control will be null.
The proper statement should be like this:
<%@ Register TagPrefix="PRE" TagName="MyControl" Src="~/templates/Units/MyControl.ascx" %>
Ref my Stack Overflow question:
http://stackoverflow.com/questions/13305213/aspnet-webforms-server-control-is-null-in-page-load

2013-11-11

Apple iPhone 4 not showing up in Windows Live Photogallery on Windows 7

This is for iPhone 4, but may also work on other versions of iPhone.

The problem I am having is that the iPhone does not show up when I press the “Import” button in Windows Live Photogallery, and it’s been driving me nuts.

So today I fixed the problem this way:

Procedure 1 (RECOMMENDED):
1. Connect the phone to your Windows PC
2. Open Programs from the Control Panel, and then click the Programs and Features link.
3. Locate and right click the Apple Mobile Device Support application, then choose Repair.
4. Locate and right click the Apple Application Support application, then choose Repair.
5. If you have opened Windows Live Photogallery, close and restart it, then click the “Import” button (top left).

Unfortunately it seems to me that I need to do that each time I connect my iPhone, so it is somehow reverted when I restart the computer. I really think someone at Apple or Microsoft should have done a better job to avoid these problems.

If this does not fix your problem, then I must admit that I also did the following before the procedure above:

Procedure 2 (NOT RECOMMENDED/STRONGLY DISCOURAGED):
1. Connect the phone to your Windows PC
2. Open Device Manager (Right click Computer, then choose Properties, then click the Device Manager option).
3. Under “Universal Serial Bus controllers” I found at the top an entry called something starting with Apple.
4. Uninstall the driver for this.
5. Repeat Procedure 1.

Problem now is that iTunes cannot detect the phone any more.
So… I will need to repair or reinstall iTunes, which is turning out to be a nightmare from hell.

To reinstall iTunes you need to uninstall (according to http://support.apple.com/kb/ht1925):
1. iTunes
2. Apple Software Update
3. Apple Mobile Device Support
4. Bonjour
5. Apple Application Support

I needed to uninstall the following also, although it did not say so on Apple’s web page so I am unsure the web page is up to date:
6. iCloud

Then restart your computer.

Then download the latest version of iTunes from Apple, and run the installation.