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.

2013-10-21

Safe Enum Pattern

Here’s my implementation of the Safe Enum Pattern.

Why? Because Enums are kind of cumbersome to handle, and you need to use methods like Enum.Parse and Enum.ToObject etc, and you cannot compare them to string without casting them to string.

I just wanted to collect all my constant strings in one place, and also allow them to be constrained to a set of values, so that I can send them as parameters to a function knowing that only my predefined legal values will be allowed.

So to make it easy to compare them I have implemented the IEquatable<T> interface, and also operator overloading on the == and != operators, so that I can do this:

PropertyName myPropertyName = getPropertyName();
if(myPropertyName == “test”) { /*… do stuff */ }

I can also have a function like this:

public object GetPropertyValue(PropertyName propertyName)
{
    ….
}

And I am guaranteed that only my set of valid strings will be allowed as a parameter, like enums really.

Well, here’s the code:

public class SafeEnumBase : IEquatable<string>, IEquatable<SafeEnumBase>
{
    
public SafeEnumBase(string name) { Name = name; }
     public string Name { get; protected set; }
     public override string ToString() { return Name; }
     #region IEquatable<T> implementetion
     public bool Equals(string other)
     {
         return (other == Name);
     }
     public bool Equals(SafeEnumBase other)
     {
         return (other.Name == Name);
     }
     #endregion
     #region OPERATOR OVERLOADING allows comparing objects to strings and objects to objects without need to specify which property to compare
     public static bool operator ==(SafeEnumBase p1, PropertyName p2)
     {
         return p1.Equals(p2);
     }
     public static bool operator !=(SafeEnumBase p1, PropertyName p2)
     {
         return !p1.Equals(p2);
     }
     public static bool operator ==(SafeEnumBase p1, string p2)
     {
         return p1.Equals(p2);
     }
     public static bool operator !=(SafeEnumBase p1, string p2)
     {
         return !p1.Equals(p2);
     }
     #endregion


}



public sealed class PropertyName : SafeEnumBase

{
     private PropertyName(string name) : base(name) { }

     public static readonly PropertyName ID = new PropertyName("ID");
     public static readonly PropertyName NAME = new PropertyName("NAME");
     public static readonly PropertyName NUMBER = new PropertyName("NUMBER");
     public static readonly PropertyName TYPE = new PropertyName("TYPE");

}


public sealed class ClassName : SafeEnumBase
{
     private ClassName(string name) : base(name) { }


     public static readonly PropertyName CUSTOMER = new PropertyName("CUSTOMER");
     public static readonly PropertyName EMPLOYEE = new PropertyName("EMPLOYEE");
     public static readonly PropertyName ADMIN = new PropertyName("ADMIN");
     public static readonly PropertyName TYPE = new PropertyName("TYPE");
}


2013-08-27

My Instagram Tags Collection (work in progress)


Animals

#igw_animal #natureskingdom #animal_digest #petsofinstagram #petstagram

Beauty

#jaw_dropping_shots #stunning_shots #flawless_shots #instagood #all_my_own #ig_watchers #ig_captures #ig_exquisite

#jaw_dropping_shots – follow follow @jaw_dropping_shots
#stunning_shots – follow @stunning_shots
#flawless_shots – follow @flawless_shots
#instagood – follow @instagood
#all_my_own – follow @allmyown
#igw_photo – follow @ig_watchers
#ig_captures – follow @ig_captures
#ig_exquisite – follow @ig_exquisite

Children

#thechildrenoftheworld #thepursuitofjoyproject #throughachildseyes #ig_kids #instagram_kids #childofig #kids_circle #childrenphotography

City / Urban

#ig_captures_city #citybestpics #rsa_streetview #bestofmycity_2see

Europe / World

#ig_europe #world_union #worldcaptures #world_shotz #worldplaces #worldingram

Nature / Landscape

#love_natura #landscapehunters #landscape_captures #ig_captures_nature #ig_captures_landscape

Norway

#i_love_norway #ignorway #bestofnorway #beautifulnorway #visitnorway #our_amazing_norway #wu_norway #instasfromnorway #igofnorway #life_in_norway #scanshots

Sky / Clouds

#rebel_sky #cloud_skye #cloudonthehorizon #cloudwhisperers #rsa_sky

Sunset

#fairytale_sunset #sunrise_sunsets_aroundworld #sunsetsniper #all_sunsets #ig_sunsetshots #sendmeyoursunset

Travel

#mytravelgram #ourtravelgram #globe_travel #travelgram #travelingram

2013-08-26

Problem with Windows Live Photo Gallery not detecting iPhone 4

I am facing an issue which is that my iPhone 4 is not detected by Windows Live Photo Gallery. Well, sometimes it is showing up and sometimes not.

My computer is running Windows 7 Professional.

I normally connect my phone before I log on to my computer, sometimes even before I turn it on. Not sure if that makes any difference.

When I attach my iPhone, iTunes runs the long lasting process of syncronizing and backing up my phone, so attaching and detaching the phone to see if that helps gets tedious, especially since it seems that iTunes takes posession of the phone and blocks all other programs while the backup is in process, and I must wait for it to finish each time.

Sometimes it does help to detach and attach the phone though, but as I said, it’s a tedious process. There must be a better way!

2013-08-21

Generic Cache Helper

I have written a generic Cache Helper which adds new methods to any object of type T which will add the object to either the global (application) or user (session) cache. It uses the HttpContext.Current.Cache underneath.

Example on how to use the class:

public MyType GetMyObject()
{
     MyType myObject;
     if(CacheHelper.TryGetFromCache(“key”, out myObject))
     {
          return myObject;
     }
     //fetch/create a new object, then cache it and return it
     myObject = CreateNewMyObject();
     myObject.AddToApplicationCache(“key”);
     return myObject;
}

Here’s the code for the Cache Helper:

public static class CacheHelper
{
    public static void AddToSessionCache<T>(this T item, string key) where T : class
    {

        HttpContext.Current.Session.Add(key, item);
    }
    public static void AddToApplicationCache<T>(this T item, string key) where T : class
    {
        AddToApplicationCache(item, key, Cache.NoSlidingExpiration, null);
    }

     public static void AddToApplicationCache<T>(this T item, string key, TimeSpan slidingExpiration) where T : class
    {
        AddToApplicationCache(item, key, slidingExpiration, null);
    }    

    public static void AddToApplicationCache<T>(this T item, string key, TimeSpan slidingExpiration, CacheDependency dependency) where T : class
     {
         HttpContext.Current.Cache.Add(key, item, null, Cache.NoAbsoluteExpiration, slidingExpiration, CacheItemPriority.Normal, null);
     }

     public static bool TryGetFromCache<T>(string key, out T item) where T : class
     {
         if (HttpContext.Current.Session[key] != null)
         {
             item = HttpContext.Current.Session[key] as T;
             return true;
         }
         if (HttpContext.Current.Cache[key] != null)
         {
             item = HttpContext.Current.Cache[key] as T;
             return true;
         }
         item = null;
         return false;
     }
}

Please use as you will, and at your own risk.