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.

2013-03-21

Fiddler tricks

Capture traffic from localhost:
  • Add a dot after “localhost”, so it becomes http://localhost.
    • This does not always work. On my Windows Server 2008 R2 box, it does not.
  • Access your web using the (netbios) machine name.
  • Access your web through the fiddler proxy: http://ipv4.fiddler/AppName
  • Run your web’s application pool under the same account that fiddler is running under, ie. the account you are logged on as.
    • NB! This also has the MAJOR benefit that you will see web service calls from your website.
    • IIS Express by default runs as the logged on user, so Fiddler will capture traffic.
Source:
http://weblogs.asp.net/lorenh/archive/2008/01/10/tip-for-using-fiddler-on-localhost.aspx

2012-08-03

Debugging log4net

Enable internal logging by adding the following to appSettings:
<add key="log4net.Internal.Debug" value="true"/>

More details in this thread on Stack Overflow:
http://stackoverflow.com/questions/3121975/log4net-appenders-not-working-in-iis7-5/3126675#3126675

2012-05-02

Why is Windows 7 so slow?

After I’ve been looking for a solution for my wife’s new 64 bit gamer PC for some time (and still haven’t found a satisfactory solution), these proposed solutions may or may not work (use at your own risk):
Windows Shell:
  • Shell Extensions:
    • Run Auturuns.exe or ShellExView.
    • Disable/uninstall etc extensions/programs that are started automatically.
    • Some that may be disabled as an attempt:
      • Nero/Nero Scout.
      • VirtualCloneDrive
      • Power Archiver 2011
  • Optimizing folders for images/videos etc.
    • Windows is continuously trying to optimize your folders for whatever is in them, but that process is quite expensive.
    • Set all folders to be optimized for “General Items”, then you can set the ones you want to be optimized for other stuff to whatever as you wish (and at a performance cost) afterwards.
  • Windows Search Index
    • Disable/turn off.
  • Antivirus software real time protection.
    • Turn off (at own risk)
  • User profile issues
    • You may have an issue with your user account. Try to create a new user account, and check if that account has the same problems.
Internet Explorer:
  • Turn off addons.
    • To run without addons, start IE using “iexplore.exe –extoff” in Start/Run.
Firefox:
  • Is maintaining a 50M+ database of malicious web sites which is synchronized (at startup maybe? or in the background?).
    • May be turned off (at your own risk) if you have healthy browsing habits and don’t click just any links.
  • Turn off addons.
Source(s):
UPDATE:
The reason the PC was so slow seems to be the SSD disk on which Windows is installed. Googling it turned up several people with problems, and also some guy at the retailer (Komplett.no) confirmed that there could be some issues with it. Now just waiting for my wife to make her backups so we can return the PC to the retailer for repairs.

2012-03-13

VMWare disk crash

I was going to a meeting, so I just folded my laptop shut and was off. After the meeting my vmware disk image was corrupt.

So what to do?

I downloaded the Virtual Disk Development Kit (requires registration), and pretty much followed this recipe: http://blog.ijun.org/2011/10/vmware-specific-virtual-disk-needs.html.

Then attempted to start the VM, but starting it seems to corrupt the disk again, so…

Repaired the disk again, and then mounted it on my laptop, using the vmware-mount command from the Virtual Disk Development Kit. MARK: The mounted drive was only accessible through the same command window where the mount command was run. I was then able to XCOPY all my files, so that I can copy them to a new vmware image and continue my work.

2012-02-16

BSOD on Lenovo ThinkPad W510 w/Intel SSD

I have a Lenovo ThinkPad W510 with intel SSD (about 75 Gigs). I’ve been having a lot of bluescreens, but now I think I’ve solved the problem by a firmware update on my SSD.

My first problem was that I do not have an alternate boot device: no floppy and no CD/DVD drive, so I had to make a bootable USB Flash Drive, and boot from it. Here’s how to do that: http://arstechnica.com/business/news/2009/12/-the-usb-flash-drive.ars, or even like this: http://johnpapa.net/BootFromUSB. Come to think of it, it’s always nice to have an alternative boot device available, as a sort of Windows rescue disk.

So after that I downloaded the Intel Firmware Update Tool: http://downloadcenter.intel.com/Detail_Desc.aspx?agr=Y&DwnldID=18363.

Copy the tool to the flash drive.

Boot from flash drive, then run the tool. Booting from the flash drive might require you to enter into the BIOS setup to change the boot sequence so that an attempt to boot from the USB device is made.

No BSOD (Blue Screen of Death) for 2 weeks now, and I used to have them at least once a day, one day I had one every hour or so.

Here’s an alternative path with full description:
http://communities.intel.com/thread/8906

Hope this helps someone.

2012-01-03

Debugging Windows BSOD (Windows 7)

Here are some steps to take if your Windows PC regularly crashes, showing the infamous Blue Screen of Death (BSOD):

  1. Download and install the “Debugging Tools for Windows” x64 or x86 depending on your hardware architecture.
  2. Set path to symbol files.
  3. Start WinDbg, and select “Open Crash Dump” from the File menu.
  4. Select the latest crash dump file.
  5. Read the output, at the bottom you will find the likely cause of the crash.

This is the full story: http://www.networkworld.com/supp/2011/041811-windows-7-crashes.html?page=1