2010-09-13

Pregnancy ticker

The following HTML is a pregnancy ticker. The HTML fetches an image from http://www.3dpregnancyticker.com. Click on the image to go to the web site. To put in your own due date you will need to change the values for the “dob” and “doc” variables. It may be used as a desktop item on Windows. I have also used it on a HTML Screen Saver.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
<div style="height:100%;width:100%;vertical-align:middle;text-align:center;background-color:MidnightBlue;">
<table id="kwsTickerLayoutTable" border="0" cellspacing="2" cellpadding="1" style="background-color:#FFEEFF;text-align:left;">
<tr><td rowspan="3" style="background-color:green;"><a id="kwsTickerCountdownUrl" href="" style="border:0;"><img id="kwsTickerCountdownImage" width="100px" alt="" src="" style="border: 1px solid #EEDDEE;" /></a></td><td style="font-style:normal; font-family: Arial; font-size: x-large; font-weight: bold; font-variant: normal; color: #008080;"><label id="kwsTickerCountdownText1">test</label></td></tr>
<tr><td style="font-style:normal; font-family: Arial; font-size: x-large; font-weight: bold; font-variant: normal; color: #008080;"><label id="kwsTickerCountdownText2">test</label></td></tr>
<tr><td style="font-style:normal; font-family: Arial; font-size: x-large; font-weight: bold; font-variant: normal; color: #008080;"><label id="kwsTickerCountdownText3">test</label></td></tr>
</table>
</div>
</body>
<script language="javascript" type="text/javascript">
    var now = new Date(); //today
    var dob = new Date(2011, 2, 9); //date of birth
    var doc = new Date(2010, 5, 1); //start date of pregnancy
    var one_day = 1000 * 60 * 60 * 24; //milliseconds in one day
    var days_total = Math.ceil((dob.getTime() - now.getTime()) / (one_day)); //number of days left
    var weeks = Math.floor(days_total / 7); //number of weeks left
    var days = days_total % 7; //number of days in addition to the weeks left
    var days_gone_total = Math.ceil((now.getTime() - doc.getTime()) / one_day); //number of days gone
    var weeks_gone = Math.floor(days_gone_total / 7); //number of weeks gone
    var days_gone = days_gone_total % 7; //number of days in addition to the weeks gone
    var lab1 = document.getElementById('kwsTickerCountdownText1'); //get label 1
    var lab2 = document.getElementById('kwsTickerCountdownText2'); //get label 2
    var lab3 = document.getElementById('kwsTickerCountdownText3'); //get label 3
    var img = document.getElementById('kwsTickerCountdownImage'); //get image element
    var url = document.getElementById('kwsTickerCountdownUrl'); // get url element of image element
    lab1.innerHTML = (weeks_gone + 1) + 'th week';
    lab2.innerHTML = weeks_gone + ' weeks and ' + days_gone + ' days on the way.';
    if (days > 0) { lab3.innerHTML = 'Only ' + weeks + ' weeks and ' + days + ' days left!'; }
    else { lab3.innerHTML = 'Only ' + weeks + ' weeks left!'; }
    img.setAttribute('src', 'http://images.3dpregnancy.com/en/2D/200/' + weeks_gone + '-weeks-pregnant.jpg');
    url.setAttribute('href', 'http://3dpregnancy.parentsconnect.com/calendar/' + weeks_gone + '-weeks-pregnant.html');
</script>
</html>

2010-06-14

SQL Server 2008 Client Tools Install Pain

In this blog post http://nomisit.wordpress.com/2009/04/21/installing-sql-server-2008-client-tools-what-a-pain/ it is described how you need to upgrade Visual Studio 2008 to SP1 if you are installing any of these…

  • BIDS
  • Management tools (Basic or Full version)
  • Integration Services
  • … and you have previously installed VS2008, then you will need to upgrade it to SP1.

    I did install a trial version of VS2008 but now I have uninstalled everything, but still getting the same failed requirement.

    So now I am trying to install SP1, even if I don’t know what products it could be upgrading since I removed them all. Perhaps it is something like a C++ runtime or something that was left behind by the uninstaller?

    The SP1 installer seemed to be stuck on “WebDesignerCore_KB950278”. But proceeded after quite a while (20 minutes, maybe more).

    Then it took a long time to install “VS90sp1-KB945140-X86-ENU”.

    I got a Fatal Error at the end of the install, so now I don’t know what was installed or not. So either try to reinstall SP1 or try to install the client tools?

    Tried to install client tools, and to my surprise it succeeded!

    2010-05-19

    Wrapping Web Service Proxy objects to Common Cargos using Serialization

    In my previous post I described a way to wrap web service proxy objects to common cargo objects using reflection. This method works only for objects with only value type properties.

    Update: The performance of this code may not be the best.

    internal U wrapToCargoBySerialization<T, U>(T source, U target)
    {
        UTF8Encoding encoding = new UTF8Encoding(true);

        XmlRootAttribute rootAttribute = new XmlRootAttribute();
        XmlSerializer xmlSerializerSource = new XmlSerializer(typeof(T), rootAttribute);
        MemoryStream stream = new MemoryStream();
        xmlSerializerSource.Serialize(stream, source);
        string xml = encoding.GetString(stream.ToArray());
        xml = xml.Replace("<?xml version=\"1.0\"?>", string.Empty);

        MemoryStream ms = new MemoryStream(encoding.GetBytes(xml));

        XmlSerializer xmlSerializerTarget = new XmlSerializer(typeof(U),rootAttribute);

        return (U)xmlSerializerTarget.Deserialize(ms);
    }

    Usage example:
    CommonObjects.Customer cust;
    cust = wrapToCargoBySerialization(wsCustomer, cust);

    Note that I had to remove the <?xml … /> declaration before deserializing.

    A prerequisite for using this method is that the objects have the same structure. To achieve this I simply copy the web service objects from the web reference to a common cargo project. The common objects are used for passing information between layers in the application.

    2010-04-29

    Windows Installer Cleanup Utility

    Freeing up space on your hard disks is an ever ongoing battle for some people, for instance if you at some point decided on a too small system partition (“10 Gigs must surely be enough?”).

    So in the Windows directory (on Windows XP at least) there is a folder called “Installer” where many install files will be found. It may be tempting to just delete all files here, freeing up many gigs of space, but that could cause problems later, for instance if you want to upgrade some program that needs the old version to be uninstalled first.

    So this is where the Windows Installer Cleanup Utility comes into play. Read this excellent blog post on where to get it and how to use it: http://blogs.msdn.com/heaths/archive/2007/01/31/how-to-safely-delete-orphaned-patches.aspx

    Essentially after installing the utility, you may run a command that will delete orphaned installation files, that is install files for programs that are no longer on your system.

    I managed to free up enough space to install MS VS 2008 Professional… :)

    2010-04-13

    Syncroniziong files with FreeCommander and Compare It!

    Up until now I have mostly used SourceSafe and TFS for comparing files. Recently I had a situation where I had to do a so called “Baseless Merge” in TFS. This worked quite well for most files. Then there were some files that were not as easy to merge. So a manual merge was required. Not being quite happy with the file comparing offered by VS, I searched and found a nice option:

    • Use FreeCommander to find all files that have differences.
    • Use Compare It! to compare and syncronize the contents of files.

    To be able to use the “Compare left and right sides” option in FreeCommander, you need to go into Extras –> Settings in FreeCommander, in the Programs section, and set “Compare files” to “C:\Program Files\Compare It!\wincmp3.exe” assuming that’s where Compare It! is installed.

    FreeCommander may be found at http://www.freecommander.com.

    Compare It! may be found at http://www.grigsoft.com.

    I think using these two great tools together is synergy in action!

    2010-04-09

    Chinese comments

    I have been getting some comments, I am guessing they are in Chinese. This may seem unnecessary to point out, but anyway here goes:

    I DON’T UNDERSTAND CHINESE!

    So please stop commenting in any languages except English, or in some rare cases where I have blogged in Norwegian where this language may be used (I also understand Swedish and Danish and a bit of German).

    2010-02-26

    Common Table Expression for Database Structure

    When copying data from one database to another, breaking constraints is always a problem. If you do not insert data in a certain sequence, you will get foreign key violations. So I tried to work out a CTE that starts with all tables that have no foreign keys, then the tables referencing them, then the once referencing them again, and so on… So came up with this:

    WITH CTE (name,object_id, lvl)
    AS
    (
        select name, object_id, 0 AS lvl from sys.tables
        where object_id NOT IN (select parent_object_id from sys.foreign_keys)
       
    UNION ALL

        select tbls.name, tbls.object_id , lvl + 1 from sys.tables tbls
        join sys.foreign_keys keys on tbls.object_id = keys.parent_object_id
        join CTE on CTE.object_id =  keys.referenced_object_id
    )
    SELECT * FROM CTE
    OPTION (MAXRECURSION 10000)

    Note that this will not work if you have self-referencing tables, ie. tables that have a foreign key pointing to its own primary key. Also the same tables may appear many times because they reference the same tables. And also if the same table have many foreign keys it will appear many times.

    The conclusion is that this does not solve my problem, but it was fun to create the CTE anyway.

    2010-02-16

    Experiences on upgrading EPiServer 4.51 to 4.62B part 2

    Ok, so the upgrade has been done, but will the project compile?

    Sadly the answer is no.

    I got the exact same problems described here: http://world.episerver.com/templates/forum/pages/thread.aspx?id=19575&epslanguage=en. It took some time for me to understand the answer to the part they did give an answer to. They didn’t answer the second question at all.

    Problem 1: WsrpHelper doesn’t exist any more

    My solution, which saves me from having to go through 8-10 places and correct the code, was to create a new class inside the WsrpPortal.aspx.cs file:

    class WsrpHelper
    {
        public static IConsumerEnvironment ConsumerEnvironment
        {
            get { return ElektroPost.Wsrp.Consumer.ConsumerContext.ConsumerEnvironment; }
            set { ElektroPost.Wsrp.Consumer.ConsumerContext.ConsumerEnvironment = value; }
        }

        public static void EnsureConsumerEnvironment()
        {
            if (ElektroPost.Wsrp.Consumer.ConsumerContext.ConsumerEnvironment == null)
            {
                ElektroPost.Wsrp.Consumer.ConsumerContext.ConsumerEnvironment = ConsumerFactory.ConsumerEnvironmentInstance();
            }
        }
    }

    Problem 2: LanguageManager.GetContextLanguage() is obsolete

    It says in the error message that you should use LanguageContext.Current as a replacement, but that would create a type conversion exception.

    I am guessing that you can to use LanguageContext.Current.CurrentUILanguageID as a replacement for GetContextLanguage() (please do correct me if I’m wrong).

    DISCLAIMER:
    I haven’t been able to test my solution, since the webs I am working on don’t actually use the portal framework. My code compiles now, so the web is up and running, and I am happy for the time being. If anyone finds any flaw in my solutions please don’t hesistate to leave a comment.

    2010-02-15

    The EPiServer Offline Package is a ZIP-file

    So if you for instance need to just upgrade the database, not the whole EPiServer installation, you can just rename the offline upgrade package from .pkg to .zip, and you will find all the files used by the upgrade wizard inside.

    Ypou can create an offline upgrade package from and to the versions you want using the EPiServer Manager, as mentioned in my previous post.

    The database scripts are located in the “Upgrade” folder, and if you sort them ascending by name and run them in that order, you should be able to upgrade the database “manually”.

    Scenarios where this method may be used may be

    • you did/tested the upgrade in your development environment and then deployed the upgraded files
    • you have already upgraded EPiServer on a staging server and the production database (which is an earlier version) should be restored on the staging server

    The EPiServer Manager does other things than just copying files, like registering components in the GAC, so use the EPiServer Manager whenever possible. Also, remember to always have nescessary backups available.

    2010-02-12

    Experiences from upgrading EPiServer from version 4.51 to 4.62B

    Ok, so previously I have upgraded my project files and solutions from Visual Studio 2003 to 2008, and have upgraded to master pages. I wrote about this in an earlier post: http://stgaup.blogspot.com/2010/02/upgrading-episerver-to-masterpages.html.

    So now the next step. Upgrading the EPiServer version from 4.51 to 4.62B.

    Since I am going to upgrade at least 2 sites, and someone in IT Operations needs to do the same upgrade on the production systems, I thought it would be a good idea to create an offline install. I had to google a bit and eventually fond out that to create an offline package, you need to:

    1. Start EPiServer Manager
    2. On the Tools menu, select “Create offline installation…”
    3. Click Next
    4. Select “Upgrade”
    5. Select From version in my case 4.51)
    6. Select To Version (4.62B)
    7. Specify directory where the package should be created.
    8. Click “Create”.

    I had no problems with this part of the job.

    Next I had to do the upgrade:

    1. Backup all files and the EPiServer database.
    2. Right-click the web site to upgrade in the EPiServer Manager, and select “Upgrade…”.
    3. Click Next.
    4. Select “Offline” and then browse to the package created before.
    5. Click Next.
    6. Review upgrade info, then click “Upgrade”.

    The next thing happening was that the upgrade was being done, and the progress bar was showing some progress, until about 20% on the way. Then I got an error message: “Failed to register ASP.NET client scripts on this site”

    It turns out that the EPiServer Manager is not able to install when there are versions of the .NET Framework installed after version 2.0. So the dirty trick you need to do is to remove the 3.0 and 3.5 folders from the WINDOWS\Microsoft .NET\Framework folder because EPiServer Manager will try to locate aspnet_regiis.exe (and maybe other command line utilities) in those folders, and it’s not there. This thread was helpful: http://world.episerver.com/Templates/Forum/Pages/Thread.aspx?id=17376&epslanguage=en.

    Ok, so after I had moved those folders, it seemed that the upgrade worked, until I tried to browse the web:

    EPiServer 4.62.0.533 can only be used with database version 100, current version is 90. Make sure both database and assemblies are upgraded correctly.

    I didn’t get any errors while upgrading. Everything seemed to go well, but it didn’t. The EPiServer Manager failed to upgrade the database.

    I am assuming at this point that the database upgrade failed because the web was using Windows Integrated security with SQL Server. I thought it could work because I had made sure that my windows user account had owner rights to the database, but sadly it failed.

    Tip: Don’t use Windows Integrated Security with EPiServer (when upgrading) even though Microsoft recommends that as the most secure way of accessing SQL Server. If you do, you will (probably) need to set up your site with impersonation, and turn off anonymous access.

    Ok, so then I tried to run the upgrade once more after setting a SQL Server username/password. I then got the message:

    The site is already up to date (4.62.0.533) – no new versions available.

    So now time for my next dirty trick, one that I have used before, which is to copy the old EPiServer.dll back into the bin folder of the web site. (Of course I had a backup.)

    So new upgrade attempt. First had to restart the EPiServer Manager, because it still thoght the web was version 4.62B. After restarting it said 4.51, as I intended it to.

    This time the upgrade worked as it should, and the web is up and runnig again, now og EPiServer 4.62B.

    IMPORTANT: Copy back the .NET 3.0 and 3.5 Framwork files to their correct location!

    NEXT STEP: Upgrade to CMS 5? Am I brave enough?

    2010-02-10

    My Second SmallBasic program

    This one draws a sinus curve (well a cosinus curve):

    GraphicsWindow.Title = "Hello World!"
    GraphicsWindow.BackgroundColor = "Yellow"
    GraphicsWindow.Width = 320
    GraphicsWindow.Height = 200
    GraphicsWindow.Show()

    oldx = 0
    oldy = Math.Cos(0) * 100 + 100

    For x = 1 To 320
      y = Math.Cos(x/10) * 100 + 100
      GraphicsWindow.DrawLine(oldx,oldy,x,y)
      oldx = x
      oldy = y
    EndFor

    My first SmallBasic program

    Ok, my first was “Hello World”, but this is my first using the GraphicsWindow:

    GraphicsWindow.Title = "Hello World!"
    GraphicsWindow.BackgroundColor = "Yellow"
    GraphicsWindow.Width = 320
    GraphicsWindow.Height = 200
    GraphicsWindow.Show()

    oldx = Math.Sin(0) * 100 + 160
    oldy = Math.Cos(0) * 100 + 100

    For i = 0.1 To 2 * Math.Pi Step 0.1
      x = Math.Sin(i) * 100 + 160
      y = Math.Cos(i) * 100 + 100
      GraphicsWindow.DrawLine(oldx,oldy,x,y)
      oldx = x
      oldy = y
    EndFor

    What does it do? It draws a circle. Great huh? Oh I could have used GraphicsWindow.DrawCircle? Amazing stuff :P

    Btw SmallBasic may be downloaded from http://msdn.microsoft.com/en-us/devlabs/cc950524.aspx.

    2010-02-05

    Upgrading EPiServer to MasterPages

    Initial Status:
    I have already upgraded the EPiServer solution from Visual Studio 2003 / .NET 1.1 to Visual Studio 2008 / .NET 2.0/3.5. First upgraded to VS2005/.NET 2.0 by opening the projects in VS2005 and using the wizard, then converting the project to a web application. Then did the same again, opening the project in VS 2008. Everything seemed to work fine after the upgrade. So next step is to upgrade from using EPiServer:DefaultFramework to using master pages.

    Next steps:
    I found the (very good I might add) article: http://world.episerver.com/Articles/Items/Experiences-from-migrating-to-EPiServer-461-and-ASPNET-20/ and tried to follow the steps described from the section called “Upgrading your custom templates to ASP.NET 2.0”. However there seems to be some little information missing:

    1. In addition to changing the <@ Control … to <@ Master … you must also in code-behind change the inheritance so that the master page inherits from System.Web.UI.MasterPage in stead of EPiServer.WebControls.ContentFramework.
      This will cause some problems:
      1. If you have any references to CurrentPage, you will need to fix it. I fixed it by creating a new property on the master page called CurrentPage:

        public PageData CurrentPage
        {
            get
            {
                PageBase pb = (PageBase)this.Page;
                return pb.CurrentPage;
            }
        }

      2. Also if you are using any commands that are not prefixed and are using functionality from the previous base class you will need to fix them:
        1. Translate(…) => EPiServer.Global.EPLang.Translate(…)
          I solved this by creating a private function in the master page code-behind, which saved me from changing code in multiple places:
        2. private string Translate(string key)
          {
              return EPiServer.Global.EPLang.Translate(key);
          }

        3. GetPage(…) => EPiServer.Global.EPDataFactory.GetPage(…)
          Again I solved it by creating a private function with the same name:
        4. private PageData GetPage(PageReference pageLink)
          {
              return EPiServer.Global.EPDataFactory.GetPage(pageLink);
          }

    2. The process of converting from the 1.1 style of declaring the controls in code-behind to the 2.0 way using the .designer.cs file is not always working as is should. I had to go into the code-behind file and remove declarations of controls, and then made a slight change to the front master page file, and the saved it, so that the controls using the runat=”server” attribute were (automatically) declared in the designer.cs file. Also some events vere explicitly declared in code-behind (opposed to the new way of using “AutoEventWireup=True”. I just removed them as they were doing nothing anyway.

    3. Also had a small problem due to some additions to the asp.net control gallery and poor naming conventions. The old EPiServer Content Framework files declared a conrtol called simply “Menu”. This name crashes with the “System.Web.UI.WebControls.Menu” web control, so I just changed the name.

    And now my web is up and running with EPiServer 4.51 (on VS2008) and using Master Pages (on only one page so far: default.aspx). After changing all aspx-web forms so that they use the new master page, the next step will be to upgrade EPiServer to 4.62B, and thanks to the previously linked article this should hopefully be a piece of cake.

    2010-01-29

    Moving log files

    I am using log4net and other logging in my apps, and the logs are filling up the disks of the test server, so I created a Windows Scheduled Task to move logs to an archive disk, and also delete very old logs from the archive. I move logs older than 2 weeks to the archive and delete logs older than a year from that archive. I created this vb-script (started from the scheduled task) to do the job:

    'VBScript that moves old log files from C:\LogFiles to E:\LogArchive

    'Folders
    Const FOLDER = "C:\LogFiles" 
    Const BACKUP_FOLDER = "E:\LogArchive" 

    'Objects
    Dim objFSO, objFolder, objFolder2, objFile 
    Set objFSO = CreateObject("Scripting.FileSystemObject") 
    Set objFolder = objFSO.GetFolder(FOLDER)

    'Loop and move
    For Each objFile In objFolder.Files 
      If objFile.DateLastModified < DateAdd("w", -2, Now) Then 
        objFile.Move BACKUP_FOLDER & "\" & objFile.Name 
      End If 
    Next

    'Delete very old files from target BACKUP_FOLDER
    Set objFolder2 = objFSO.GetFolder(BACKUP_FOLDER)
    For Each objFile In objFolder2.Files 
      If objFile.DateLastModified < DateAdd("w", -52, Now) Then 
        objFile.Delete
      End If 
    Next

    Plain old ASP-like code. No Types, everything is just Variant types.

    2009-12-16

    Check if any new properties have been added in EPiServer 4.x

    The scenario for this is that you have a Test server and a Production server. You are rolling out all changes that have been tested on the Test server to the Production server. You did, being a pro and all, of course make a note of all the changes that were done to properties on the Test server since the last rollout to Production, but just to make sure you want to check what new properties have been added.

    Step 1

    Add the Production server as a linked server in SQL Server Management Studio on the Test server, in this example called [LinkedServer].

    Step 2

    Create a new query on the Test server and paste the following query into it. You will need to substitute the names of the database and linked server with names from your environment.

    -- CHECKS IF ANY NEW FIELDS HAVE BEEN ADDED ON THE TEST SERVER
    -- THAT DO NOT EXIST ON THE PRODUCTION SERVER
    USE EPiServerDb;
    GO

    IF EXISTS(
        SELECT testTable.pkID, prodTable.pkID
        FROM tblPageDefinition testTable
        LEFT JOIN [LinkedServer].[EPiServerDb].[dbo].[tblPageDefinition] prodTable 
            ON testTable.pkID = prodTable.pkID
        WHERE prodTable.pkID IS NULL)
    BEGIN
        PRINT 'NEW PAGE PROPERTIES DETECTED!'
        SELECT pt.Name, pd.Name
        FROM tblPageType pt JOIN tblPageDefinition pd ON pt.pkID = pd.fkPageTypeID
        WHERE pd.pkID IN (
        SELECT testTable.pkID
        FROM tblPageDefinition testTable
        LEFT JOIN [LinkedServer].[EPiServerDb].[dbo].[tblPageDefinition] prodTable 
            ON testTable.pkID = prodTable.pkID
        WHERE prodTable.pkID IS NULL)
    END
    ELSE BEGIN
        PRINT 'NO NEW PROPERTIES DETECTED.'
    END

    Step 3

    If any new properties have been added, you will see a list of the names of page templates and what properties are new.

    This script was tested on EPiServer 4.61/62 only, but may also work for newer versions of EPiServer.

    2009-11-06

    Generic Object Factory

    The following class is a generic object factory. It is used for creating instances of objects from configured or otherwise provided strings.

    The “User Guide” is in the comments.

    /// <summary>
    /// Generic object factory that creates instances of objects from configured or otherwise provided strings.
    /// </summary>
    public class ObjectFactory
    {
        /// <summary>
        /// Creates an instance of a class from a string "[namespace.[...].className], [component without filname extension],[Version],[Culture],[…]".
        /// </summary>
        /// <typeparam name="T">The type to create.</typeparam>
        /// <param name="configuredClassAndAssembly">Format: [namespace.[...].className], [component without filname extension]</param>
        /// <returns>An object of type T.</returns>
        /// <remarks>This method uses generics!</remarks>
        public static T CreateClassInstance<T>(string configuredClassAndAssembly)
        {
            //Get type to instanciate
            Type tp = Type.GetType(configuredClassAndAssembly, true);

            //load assembly
            Assembly assembly = Assembly.GetAssembly(tp);

            //create class instance
            T instance = (T)assembly.CreateInstance(tp.FullName);

            //return instance
            return instance;
        }
    }

    I am using it to create instances of objects that implement certain interfaces, so that I can swap the implementation, or even mock it, by changing the configuration.

    The string that tells which object to create uses the format of the Type.GetType(string) string.

    Some error handling should be added.

    2009-10-05

    Skjermbrev (in Norwegian)

    Jeg kom opp i en problemstilling pÃ¥ jobben der jeg trengte et ord for “bekreftelses-e-post”, og sÃ¥ lurte jeg pÃ¥ hva man da skal bruke, for jeg synes det ser litt rart ut med disse alternativene:

    • bekreftelsese-post
    • bekreftelses-e-post (bryter regel om bruk av bindestrek)
    • bekreftelses e-post (bryter regel om orddeling)

    Det er jo anbefalt Ã¥ bruke ordet “e-post” for det som pÃ¥ engelsk heter e-mail.

    Jeg sendte derfor spørsmÃ¥let til Per Egil Hegge i Aftenposten, og fikk følgende svar: “Du løser dette ved Ã¥ bruke mitt favorittord: skjermbrev.”

    SÃ¥ nÃ¥ vet jeg (og dere) det. Fra nÃ¥ av skal jeg prøve Ã¥ snike inn ordet “skjermbrev” alle steder det er mulig :D

    2009-10-02

    Styles missing in EPiServer Edit/Admin mode

    If you ever experience this, it’s probably because EPiServer uses a custom remapping for the 404 – Page Not Found error in IIS. To fix it do the following:

    1. Open IIS manager, and right click on the web site.
    2. Select “Properties” from the dropdown menu.
    3. On the “Custom Errors” tab, scroll down the list until you see “404” in the HTTP Error column.
    4. Double click the 404 entry to open the properties box.
    5. Set the Message type to “URL”.
    6. Type “/util/NotFound.aspx” in the URL text box.
    7. Click “OK”.
    8. Click “OK” in the web site properties dialog to close it.
    9. That’s it, now Bob’s your Uncle!

    2009-09-21

    EPiServer declines to support XForms on IE8 for CMS 4.x

    According to this thread http://world.episerver.com/Forum/Pages/Thread.aspx?id=28931&epslanguage=en it seems that EPiServer is denying responsibility to make XForms on EPiServer 4.x work with IE8 since IE8 was released after EPiServer 4.x.

    The customers are experiencing an error when loading XForms with radiobuttons and/or checkboxes. The error is “invalid form” (translated from the Norwegian “ugyldig skjema”).

    UPDATE 2011-01-17: Also I have experienced that in IE8, the submit button will not submit the xform which is strange, since it should be calling a javascript function: “return(false)”, and then specifying an action string.

    In the comments to this posting, Björn Sållarp has proposed a solution from his blog: http://blog.sallarp.com/episerver-xforms-ie8/

    Save power on the cell phone

    My HTC S730 is using a lot of power, and has little standby time. Recently it stopped working, so I played with the settings, and by setting the Band Select (“BÃ¥ndvalg” in Norwegian, and number 3 on the Settings menu) to a fixed value in stead of using the “Auto” option, my phone now uses a lot less power. I selected the “GSM” network type and the “Euro band” band type. My standby time used to be like one to two days, but now its about twice that.

    2009-09-11

    Getting paths for an application

    I am creating an application that needs to load an assembly dynamically from the bin-folder of the application. This is not as straight forward as one might think.

    So I tried the following:

    string s1 = Directory.GetCurrentDirectory();
    string s2 = Environment.CurrentDirectory;
    string s3 = Assembly.GetExecutingAssembly().Location;
    string s4 = new DirectoryInfo("~/bin").FullName;
    string s5 = new DirectoryInfo("/bin").FullName;
    string s6 = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
    string s7 = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    string s8 = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);

    Results:

    s1 = s2 = “C:\Windows\system32”

    s3 = "C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\Temporary ASP.NET Files\\root\\101551d3\\93890f66\\assembly\\dl3\\f2069ce7\\fe4f0aea_dc32ca01\\MyAssemblyName.DLL"

    s4 = "C:\\WINDOWS\\system32\\~\\bin"

    s5 = "C:\\bin"

    s6 = "C:\\Documents and Settings\\MyMachineName\\ASPNET\\Local Settings\\Application Data" (getting desperate, I know)

    s7 = "C:\\Documents and Settings\\MyMachineName\\ASPNET\\Application Data"

    Finally found one that worked:

    s8 = “file:\\C:\\DevProjects\\…\\MyAppDir\\bin

    2009-08-24

    Bare linefeeds in SMTP Messages, status 451

    I was having a problem with mails that were not being sent as they were supposed to be, and the problem could be caused by the use of bare linefeeds in the message body.

    A bare linefeed is a linefeed that has only a linefeed (LF = “\n” in C#/C++/Java, ASCII code 10 decimal) and no carriage return (CR = “\r”, ASCII code 13 decimal).

    Internet e-mail standards forbid the use of bare linefeeds, and some mailservers will reject a mail using bare linefeeds, with the status 451 (other mailservers wil accept them and just correct the mistake itself).

    In stead of using bare linefeeds, a linefeed should always come with a carriage return (CR + LF = “\r\n”).

    Read the full story at http://www.dylanbeattie.net/docs/iis6_bare_linefeed.html.

    2009-07-01

    TIP: Defragment your VMs and VPCs

    I have several VMs (VMWare) and VPCs (MS VPC), and one of them in particular has been performing worse and worse, so I thought it could be good to defragment it.

    Now there’s internal fragmentation and there’s external fragmentation (just like indexes in SQL Server :P). The internal fragmentation is handled using the windows defragmentation tool inside the VM or VPC. External fragmentation occurs if you have set your disks to grow incrementally as needed. You could also say that all the space for your virtual disks should be reserved, and if your physical disks were defragmented in the first place, there would be no external fragmentation of your virtual disks. But if you let them grow incrementally, or your physical disk was fragmented when you created the virtual disk, there might be some fragmentation.

    So I found this excellent tool from Sysinternals: http://technet.microsoft.com/nb-no/sysinternals/bb897428(en-us).aspx

    Now I don’t need to defragment the whole physical disk. I can just defragment one file at a time. Should save me some time :)

    How to check if an assembly has been built in DEBUG or RELEASE mode

    I found this cool code that checks if an assembly has been built in debug or release mode: http://blogs.msdn.com/jb/archive/2006/06/14/631469.aspx 
    It compiles and runs using .NET 1.1, and thats what I used for building it.

    I used it on some assemblies in a solution I have, and were somewhat surprised to find that the following assemblies were reported as being debuggable:

    • EPiServer.dll (version 4.62)
    • log4net.dll
    • Microsoft.Web.Services2.dll

    This is probably done on purpose (to enable debugging), but it makes me wonder if my applications would run faster if the assemblies were built using Release mode.

    2009-06-16

    MVVM Toolkit for WPF and Silverlight

    Laurent Bugnion has created a toolkit for creating MVVM applications. He says:

    “To make development of WPF and Silverlight applications according to the Model-View-ViewModel pattern easier, I have put together a small toolkit which should speed up the creation of such applications by automating certain tasks.”

    Here’s the URL: http://geekswithblogs.net/lbugnion/archive/2009/06/14/mvvm-lsquolightrsquo-toolkit-for-wpf-and-silverlight.aspx

    2009-06-03

    The Web Platform Installer

    ScottGu’s last blog post is about the Web Platform Installer: http://weblogs.asp.net/scottgu/archive/2009/06/02/microsoft-web-platform-installer.aspx

    Looks like a very useful application for configuring your web server or web development server. It can be downloaded for free from this direct link to the installer.

    I also like very much that it integrates with the new Windows Web Application Gallery: www.microsoft.com/web/gallery. I am very likely going to use it very soon.

    2009-05-28

    Are you mocking me?

    I am learning to mock :D. I understand the principle, that you can write your unit tests without any finished methods or data sources (sometimes referred to as TDD). So just looking for nice places to start with Moq. Found a couple of nice links so far:

    http://stephenwalther.com/blog/archive/2008/06/12/tdd-introduction-to-moq.aspx

    http://blog.objectmentor.com/articles/2009/05/19/a-first-look-at-moq

    2009-05-14

    Getting started with S#arp Architecture

    I am trying to get started with S#arp Architecture, and I found some nice (short) videos at Dime Casts.NET:

    Introdction to S#arp Architecture

    Another look at Sharp Architecture- Validation, Design Decisions and Automapping

    Taking a look at how to modify the T4 templates used by Sharp Architecture

    I’ll be looking at them and creating my own test project. Should be good :)

    There should also be a good Northwind example available with the downloads from Google Code.

    2009-05-12

    Microsoft laying off 12 people in Norway

    A sad day when even MS has to start downsizing: http://www.digi.no/812605/microsoft-norge-maa-nedbemanne (Norwegian). Good luck to the twelve people laid off in Norway, and to their families.

    2009-05-08

    TSQL: Checking if an ID is in a Comma Separated String

    Ok, so the scenario is that we have a list of IDs, maybe from a checkboxlist, and we want to get the records that match those IDs from a table. So for the sake of this example, I just assume that the list of IDs is passed to my stored procedure as a varchar(8000) string. Using Northwind as an example database, heres an example of how an SP that gets products could look like:

    CREATE PROCEDURE GetProducts
    @ListOfProductsAsCSVString varchar(8000)

    AS

    SET @ListOfProductsAsCSVString = ',' + @ListOfProductsAsCSVString + ',';

    SELECT ProductID, ProductName FROM Products
    WHERE CHARINDEX(',' + CAST(ProductID as varchar(10)) + ',', @ListOfProductsAsCSVString ) > 0;

    So what I do is to first append a comma before and after the CSV-list. This is because I need to search for somthing that starts with a comma and ends with a comma, and usually a CSV-list doesn’t have a comma before the first element or after the last one. Then, in my select, I search using the CHARINDEX function for the ProductID prefixed and postfixed by a comma.

    Now, please be aware that this could lead to a possible SQL Injection attack, if you use this procedure uncritically without validating the input before passing it to this stored procedure, so use with caution.

    2009-05-02

    FileUpload for ASP.NET MVC 1.0

    I worked my way through the free Nerd Dinner chapter from ASP.NET MVC 1.0, creating my own web from the example. My web is a Food Recipe application where one can search among 7000 recipes on words in the title or ingredients.

    The web should also be able to have pictures of the food, so I needed to do some file uploading, and so I found Scott Hanselman’s article http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx. I copied some of his code, and put the parts I needed into this function (the definition of the ViewDataUploadFilesResult class is in Scott’s article):

    private List<ViewDataUploadFilesResult> uploadFiles()
    {
        var r = new List<ViewDataUploadFilesResult>();

        foreach (string file in Request.Files)
        {
            HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
            if (hpf.ContentLength == 0)
                continue;
            string savedFileName = Path.Combine(
               string.Concat(AppDomain.CurrentDomain.BaseDirectory,"images\\upload"),
               Path.GetFileName(hpf.FileName));
            hpf.SaveAs(savedFileName);

            r.Add(new ViewDataUploadFilesResult()
            {
                Name = savedFileName,
                Length = hpf.ContentLength
            });
        }
        return r;
    }

    Now, from before I had an Edit-action for the posting of my Edit View in my Controller, and from this I called the function above, as hown in the following code:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, FormCollection collection)
    {
        try
        {
            var recipe = recipeRepository.GetRecipe(id);
            recipe.RecipeDescription = Request.Form["RecipeDescription"];

    // code removed for brevity

            List<ViewDataUploadFilesResult> fileUploaded = uploadFiles();

            if (fileUploaded.Count > 0)
                recipe.RecipePictureUrl = Path.GetFileName(fileUploaded[0].Name);

            recipeRepository.Save();
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

    I also had to make some changes to my View:

    First, I had to add an “enctype” to the form element. This is done like this with the Html-helper class:

    <% using (Html.BeginForm("Edit", "<EntityController>", null, FormMethod.Post, new { @enctype = "multipart/form-data" })) {%>

    Second, to be able to use a FileOpen dialog, I had to add an attribute to the text box for entering the file name. In plain old ASP/Html, you would use:

    <input type=”file”>

    And that is also what we need to do here, except we need to use the Html-helper class like this:

    <%= Html.TextBox("RecipePictureUrl", Model.RecipePictureUrl, new { @type = "file" }) %>

    2009-04-29

    The old UDL-trick: Testing Database Connection Strings

    If you have problems creating a connection string, here’s an old trick:

    1. Create a text file and call it for instance test.udl. It’s the file type (extension) that’s important.

    2. Click (double-click) on the file to open it. A “Data Link Properties” dialog box will open.

    3. Select the provider you want from the first tab. Click “Next”.

    4. Select or type the name of the server.

    5. Provide username and password.

    6. Select database. This will only be possible if the parameters provided above are correct.

    7. Check “Allow saving passwords”.

    8. Click the “Test Connection”. If you get a message box saying the test was successful, proceed to the next step.

    9. Close the Data Link Properties.

    10. Hold shift down while right clicking on the UDL-file, then select “Open with”, then select “Notepad”.

    Voila! You now have your connection string to be copied and used in your application.

    2009-04-27

    Using TryParse

    I just figured out a way to use int.TryParse in an if-sentence.

    string myInputString = myTextBox.Text;
    int i = –1;
    if(int.TryParse(myInputString, out i) && i > 0)
    {

    //do cool stuff

    }

    This only works with the “&&” operator. If the parse fails, the second part that uses the “out” parameter from the parse, will not be run.

    2009-04-24

    Searching inside strings with LINQ2Objects

    I made a search form containing a button and a text box for entering multiple search words, and for excluding words by putting a dash in front of them. So at first I mixed LINQ2Entities with LINQ2Objects, and it didn’t work at all, but after converting from entities to objects (using the .ToList() method), things are working.

    Here’s my sample code, as always using Northwind as the database:

    protected void SearchButton_Click(object sender, EventArgs e)
    {
        using (NORTHWNDEntities context = new NORTHWNDEntities())
        {
            string[] crit = SearchBox.Text.Split(' ');
            List<string> included = new List<string>();
            List<string> excluded = new List<string>();

            for (int i = 0; i < crit.Length; i++)
            {
                if (crit[i].StartsWith("-"))
                {
                    //adds the string without the dash to the excluded collection
                    excluded.Add(crit[i].Substring(1));
                }
                else
                {
                    //adds the string to the included collection
                    included.Add(crit[i]);
                }
            }

            List<Products> products = context.Products.ToList(); //converting to objects

            var searchResult =
                from p in products
                where included.Any(i => p.ProductName.Contains(i))
                    && !excluded.Any(x => p.ProductName.Contains(x))
                select p;

            ProductsDataList.DataSource = searchResult;
            ProductsDataList.DataBind();
        }
    }

    2009-04-23

    ASP.NET MVC + Silverlight? Try MVVM + Silverlight in stead!

    I have been thinking about how it would be cool to use the new ASP.NET MVC project type with Silverlight as the “View”, and a quick google gives some interesting results.

    Some attempts have been made to use Silverlight as the view in MVC:

    In this one http://timheuer.com/blog/archive/2009/02/09/silverlight-as-a-view-in-aspnet-mvc.aspx the approach is to start with a Silverlight application, and then select ASP.NET MVC as the container-web for the Silverlight views. But it seems that this approach has some problems (just read the comments).

    In this approach http://blogs.msdn.com/jowardel/archive/2009/03/09/asp-net-mvc-silverlight.aspx, one starts out with an MVC web project, and then put Silverligh controls into the views. This solution is not usable, because it relies on using a property (some parameters) that is no longer accessible in the release version of MVC.

    The solution is: Don’t use MVC, Use MVVM!
    From the comments from the first one, it seems MVVM (http://msdn.microsoft.com/nb-no/magazine/dd458800(en-us).aspx) is the way to go (Model-View-ViewModel).

    Jonas Follesøe also have some good stuff:
    http://jonas.follesoe.no/YouCardRevisitedImplementingDependencyInjectionInSilverlight.aspx

    And this discussion provides some good links:
    http://stackoverflow.com/questions/375301/should-i-use-the-model-view-viewmodel-mvvm-pattern-in-silverlight-projects

    2009-04-22

    The fate of Linq2SQL

    The fate of Linq2SQL: http://tinyurl.com/5kcvzd is it dead or not? Only the future can tell, I guess...

    2009-04-20

    SendHttpRequest

    I made a little console application using .NET 1.1, that sends a request to an address given as parameter. It is to be used to simulate traffic on a web site. Probably could use some refinement of the code (just consider it my alpha, and that there will be no beta, RTM, etc.).

    using System;
    using System.Web;
    using System.IO;
    using System.Net;

    namespace SendHttpRequest
    {
        /// <summary>
        /// Summary description for Class1.
        /// </summary>
        class EntryPoint
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main(string[] args)
            {
                if(args.Length > 0)
                {
                    string url = args[0];

                    Uri uri = null;
                    try
                    {
                        uri = new Uri(url);
                    }
                    catch
                    {
                        Console.WriteLine("Invalid URL. No request sent.");
                        return;
                    }

                    WebRequest request = WebRequest.Create(uri);
                    request.Method = "GET";

                    WebResponse response = null;
                    try
                    {
                        response = request.GetResponse();
                        StreamReader rdr = new StreamReader(response.GetResponseStream());
                        string content = rdr.ReadToEnd();
                        Console.WriteLine(content);
                    }
                    catch (Exception ex)
                    {   
                        Console.WriteLine(ex.Message);
                        return;
                    }
                }
                else
                {
                    Console.WriteLine("Usage: SendHttpRequest {url}");
                }
            }
        }
    }

    2009-04-14

    ScottGu's Silverlight 2.0 Tutorial

    I am trying to work my way through Scott Gu's http://weblogs.asp.net/scottgu/pages/silverlight-tutorial-part-3-using-networking-to-retrieve-data-and-populate-a-datagrid.aspx tutorial.

    The tutorial contacts a service using a WebClient.

    Someone called David has posted a question regarding him getting the error "The remote server returned an error: (403) Forbidden.".

    The answer to the question is to add this line: Service.Headers.Add("user-agent", "Silverlight Sample App");

    However, the Headers have no "Add" method any more: http://msdn.microsoft.com/en-us/library/system.net.webheadercollection_members(VS.95).aspx.

    In stead I think you need to use the bold italic line in the source below:

            private void SearchBtn_Click(object sender, RoutedEventArgs e)
    {
    string topic = txtSearchTopic.Text;
    string diggUrl = string.Format("http://services.digg.com/stories/topic/{0}", topic);

    WebClient diggService = new WebClient();
    diggService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(diggService_DownloadStringCompleted);
    diggService.Headers[HttpRequestHeader.UserAgent] = "Silverlight Sample App";
    diggService.DownloadStringAsync(new Uri(diggUrl));
    }


    But this doesn't work either, because UserAgent is a restricted header that cannot be set. Attempting to set it will throw an exception:

    http://msdn.microsoft.com/en-us/library/system.net.webheadercollection(VS.95).aspx



    So is there any way of making the tutorial work? Am I barking up the wrong tree? If I find out I'll post the answer :)

    ASP.NET MVC 1.0

    Rob Conery, Scott Hanselman, Phil Haack and Scott Guthrie have come up with a book on the Model-View-Controller framework, and the first chapter describes building a simple web site using the framework.

    The chapter is free and can be downloaded from this link: http://aspnetmvcbook.s3.amazonaws.com/aspnetmvc-nerdinner_v1.pdf

    The example web site is on the net: http://www.nerddinner.com

    David Hayden has blogged about the book here: http://davidhayden.com/blog/dave/archive/2009/03/11/AnotherASPNETMVCSampleApplicationEBookTutorialNerddinner.aspx

    2009-03-25

    Creating your first Silverlight 2.0 application

    Good article with some videos that show you how to get started with Silverlight 2.0 in Visual Studio 2008: http://visualstudiomagazine.com/columns/article.aspx?editorialsid=2644

    Microsoft Patterns and Practices: Application Architecture Guide 2.0a

    I came across this excellent book while surfing yesterday: Application Architecture Guide 2.0a. It seems to be very good, taking into consideration most of the aspects of an application Architecture. It has a "Fast Track" chapter that summarises different patterns and practices, and when to use what. This chapter has references to the other chapters if one needs to go deeper in.

    Best of all: the book is free! The book can be downloaded as PDF from CodePlex: http://www.codeplex.com/AppArchGuide/Release/ProjectReleases.aspx?ReleaseId=20586

    I just discovered that there is a presentation available that summarises much of the book: http://apparch.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=17700

    The book may be a little outdated with regards to the latest developments in O/RM (Entity Framework / NHibernate etc.) and maybe some other places as well, but it gives an excellent overview, and tries to be technology-agnostic.

    2009-03-21

    Linq Flavors

     

    I am reading up on Linq, and see that there are a few types of Linq implementations. like for instance LinqToSharePoint or Linq ToFlickr. Reading this makes me think of a few other that could be useful:

    • LinqToWikipedia - for querying for information in an application
    • LinqToLiveSearch (…or Google?)
    • LinqToFacebook
    • LinqToLiveEarth (... or Google Maps) - for finding places

    2009-01-16

    Mapping Cargos to Objects returned from a Web Service using Reflection

    Background:

    When working with webservices, we wanted to use a common library of cargo objects that would be used for sending data between the tiers of the application. The Middleware tier has all the web references, and also has methods that encapsulate the web references objects, essentially wrapping them to common cargo objects. After all, we would not like to have dependencies to types that are defined in the auto-generated web service proxies.

    One way:

    One way of creating the cargo objects is to copy the code for the classes from the Reference.cs file into the common cargo objects assembly. Then you could wrap the objects from the web service dependent object to the common cargo objects which would then be passed to the application tier.

    Problem:

    It's a lot of work to type all the code for wrapping the objects...

    Solution:

    Since the cargo objects have the same properties as the web service proxy objects with the same names, it is possible to do the wrapping by using reflection, for instance using a method like this:

    private void wrapToCargo<T,U>(T source, U cargo)
    {
    //Gets all properties from the source object...
    PropertyInfo[] props = source.GetType().GetProperties();
    //Loops the properties...
    for(int i = 0; i < props.Length; i++)
    {
    //Checks if a property with the same name is present on both the source and the cargo,
    // and if the property is writeable.
    string name = props[i].Name;
    if (source.GetType().GetProperty(name) != null && cargo.GetType().GetProperty(name) != null && cargo.GetType().GetProperty(name).CanWrite)
    {
    //If so, set value of the cargo property to the value of the source property.
    cargo.GetType().GetProperty(props[i].Name).SetValue(cargo, source.GetType().GetProperty(props[i].Name).GetValue(source, null), null);
    }
    }
    }


    Alas, this generic way of wrapping cargos comes at a cost. I would suggest that one should wrap from the target (loop through properties of the target, then match with properties belonging to the source object) in stead of the source as shown above, because you will have more control of what fields should be mapped.

    2009-01-13

    Lots of cool stuff at SourceForge!

    I just discovered that SourceForge has a softwaremap at http://sourceforge.net/softwaremap with lots and lots of cool downloads.

    2009-01-12

    xp_ReadErrorLog (SQL 2005)

    The xp_ReadErrorLog extended stored procedure allows you to display the logs for SQL Server 2005 amnd also (as it turns out) the logs for SQl Server Agent.

    Usage:
    xp_ReadErrorLog - shows the default log for SQL Server.
    xp_ReadErrorLog 0,2 - shows the error log for SQL Server Agent (the second parameter means "Agent")

    Parameters:
    1 (int): Log Number
    2 (int): 1 = SQL Server, 2 = SQL Server Agent
    3 (string): Search string for searching for a log entry.
    4 (string): Another search string.

    Source: SQLTeam.com

    2008-07-21

    Update 'GDR 3068 for SQL Server Database Services 2005 ENU (KB948109)' could not be installed. Error code 1603.

    I noticed that my local SQL Server (2005, Standard Edition) was not started every day when I came to work, so I checked the event log, and found the error message from the title of this posting. Seems that there is a bug somewhere that prevents an update from being installed. There is a workaround at this address: http://support.microsoft.com/kb/925976 .

    2008-07-16

    SandcastleGUI

    I started using Sandcastle just a few days ago, and it was not very userfriendly, since it is a collection of command line utilities. Hence, I started looking for a GUI for Sandcastle, and found one at: http://www.inchl.nl/SandcastleGUI .

    It's quite easy to use, and I was quite happy with it. I then started to create a web with documentation for one of my projects, and ran into some problems. It seems Sandcastle has problems with some long names, resulting in linebreaks in a file called "filetitles.js". This results in a javascript error saying something about unterminated string constants.

    Thats why I created a small utility for fixing that file: FixFiletitlesJs.exe. Here's the code for my little utility (Console application):

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.IO;

    namespace FixFileTitlesJs
    {
        class Program
        {
            static void Main(string[] args)
            {
                if (args.Length == 0 || (args.Length > 0 && args[0] == "?"))
                {
                    Console.WriteLine("USAGE: fixfiletitlesjs filename [Y | N]");
                    return;
                }

                string filename = args[0];

                //creates a new filname by replacing ".js" at the end of the filename with ".bak"
                string backupFilename = Regex.Replace(filename, @"\.js$", ".bak");
                try
                {
                    //create a backup file
                    FileInfo fi = new FileInfo(filename);
                    fi.MoveTo(backupFilename);
                }
                catch (FileNotFoundException)
                {
                    Console.WriteLine("File not found.");
                    Console.ReadLine();
                    return;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("An exception was thrown while accessing the file: {0}", ex.Message));
                    Console.ReadLine();
                    return;
                }

                StreamWriter sw = null;
                try
                {
                    sw = File.CreateText(filename);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("An exception was thrown while accessing the file: {0}", ex.Message));
                    Console.ReadLine();
                    return;
                }

                StreamReader sr = null;
                try
                {
                    sr = File.OpenText(backupFilename);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("An exception was thrown while accessing the file: {0}", ex.Message));
                    Console.ReadLine();
                    return;
                }

                int i = 0,j = 0, k = 0;
                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();
                    j++;
                    Regex rx = new Regex("\",$");
                    while (!sr.EndOfStream && !rx.IsMatch(line) && i > 0)
                    {
                        line += sr.ReadLine();
                        j++;
                        k++;
                    }
                    sw.WriteLine(line);
                    i++;
                }
                sw.Close();
                sr.Close();

                //write result
                Console.WriteLine(string.Format("Original file renamed to: {0}", backupFilename));
                Console.WriteLine(string.Format("New file created with original name: {0}", filename));
                Console.WriteLine(string.Format("Number of lines read from source: {0}", j));
                Console.WriteLine(string.Format("Number of lines written to destination: {0}", i));
                Console.WriteLine(string.Format("Number of concatenations of lines done: {0}", k));
                Console.WriteLine();

                string reply = string.Empty;

                if (args.Length >= 2 && !string.IsNullOrEmpty(args[1]))
                {
                    reply = args[1];
                }

                while (reply.ToLower() != "y" && reply.ToLower() != "n")
                {
                    if (reply != string.Empty) Console.WriteLine("You must answer Y or N.");
                    Console.Write("Would you like to delete the backup of the original file (y/n)?");
                    reply = Console.ReadLine();
                }

                if (reply.ToLower() == "y") File.Delete(backupFilename);
            }
        }
    }

    2008-07-01

    Using MARS with SQL Native Client

    I tried using the example code from this article http://blogs.msdn.com/sqlnativeclient/archive/2006/09/27/774290.aspx  but I hade some trouble. Seems that you cannot use the System.Data.SqlClient to access MARS because it does not support using a Provider or the keyword "MARS Connection" in the connection string. This means you have to use an ADODB Connection.

    2008-06-10

    Javascript error in EPiServer admin mode ('Invalid argument')

    In this posting, Mark Bagnall describes a problem with javascript in EPiServer Edit Mode. I had the same problem. It was not possible to expand any branches in the EditTree, and the web browser reported a javascript error. Turned out I had set up my website in IIS with Windows Authentication only, to enable debugging/stepping in Visual Studio. The problem was fixed by allowing "Anonymous" access.

    2008-05-20

    T-SQL CONVERT datetime to varchar

    This script gets current date, and converts it using all existing predefined formats between 1 and 255:

    DECLARE @format int;
    CREATE TABLE #temp (format int NULL, string varchar(20) NULL, date datetime NULL)
    SET @format = 1;
    WHILE @format < 256
    BEGIN
        BEGIN TRY
            INSERT INTO #temp (format, string, date) VALUES(@format, CONVERT(varchar(20),getdate(),@format), getdate());
        END TRY
        BEGIN CATCH
        END CATCH
        SET @format = @format + 1;
    END
    SELECT * FROM #temp;
    DROP TABLE #temp;

    2008-05-15

    SQL Server 2005 XML - Msg 9402 (unable to switch the encoding)

    Had a problem converting XML from a column of type text to type xml. Someone else luckily has had the same problem:
    http://devio.wordpress.com/2008/03/04/retrieving-xml-data-in-sql-server-2005/
    .

    The solution was to convert the column from type TEXT to NVARCHAR(max), and get rid of the "encoding" part of the root tag, something like this (slightly altered from the example mentioned above):

    SELECT ID, CAST(
    REPLACE(CAST(XmlTextColumn AS NVARCHAR(MAX)), 'encoding="UTF-16"', '')
    AS XML).query('xpath to nodes') AS Node
    FROM TableName

    Another way to solve this problem is by adding a computed XML column:

    ALTER TABLE [MyTable]
        ADD MyXMLColumn AS CAST(REPLACE(CAST(MyXMLStoredAsText AS NVARCHAR(MAX)), 'encoding="UTF-16"', '') AS XML)
        PERSISTED

    If you add the persisted option, the value will be persisted with the table data, which will give better performance for read operations (slightly worse performance for insert/update operations).

    2008-05-07

    TFS Workspace Mapping

    I was getting this error: The Path <local path> is already mapped in workspace <machine name [old tfs server]>

    Turns out workspaces are cached locally and settings are found in: <DRIVE>:\Documents and Settings\<USER ID>\Local Settings\Application Data\Microsoft\Team Foundation\1.0\Cache.

    To fix my problem I opened the VS 2005 Command Prompt and entered: "tf workspaces /remove:*" which removed all my cached workspaces (refer to http://msdn.microsoft.com/en-us/library/54dkh0y3.aspx for full description of the Workspaces Command). This also cleared most of the content from the earlier mentioned file in the users Documents and Settings.

    Then, of course, I had to create a new workspace using VS 2005.

    Source: http://geekswithblogs.net/aaronsblog/archive/2006/09/11/90878.aspx

    2008-04-25

    .NET 2.0 transaction model

    How to handle transactions using ASP.NET 2.0 and SqlClient. Nice article here.

    2008-04-07

    Serialization of IDictionary objects

    By design, objects that implement IDictionary (Hashtable, SortedList, ListDictionary, or HybridDictionary) cannot be serialized. This Q&A describes a way of making these objects serializable by using (a "hidden hook"), and implementing IXmlSerializable: http://msdn2.microsoft.com/en-us/magazine/cc164135.aspx

    2008-04-03

    Using SQL Server 2005 XML and CROSS APPLY

    In my last blog entry, I used the UNPIVOT operator to get a table with products from an XML type column which were displayed as columns, to display the columns as rows. As fun as that was, it was not really a practical approach, more a way of showing how the UNPIVOT operator works.

    To get a similar result, without using UNPIVOT, using in stead the values() function with the CROSS APPLY operator, we could use this query:

    SELECT
    ContractNumber,
    col.value('Name[1]', 'nvarchar(50)') AS ProductName
    FROM Contract
    CROSS APPLY contractXML.nodes('Contract/Order/OrderItem') AS x(col)

    This could give a table like this if there were only one contract in the table with ContractNumber = 1:

    ContractNumber ProductName
    1 Product 1
    1 Product 1
    1 Product 2


    The nodes() function returns a table "x" with one column "col".

    The CROSS APPLY operator joins the result from a table-valued function with the result of an "ordinary" query. This is like a LEFT JOIN, only against a table returned by a function in stead of another table.

    2008-03-10

    Using SQL Server 2005 XML And Unpivot

    I have a table with contracts stored as XML. Using the XML query possibilities in SQL Server 2005 together with the UNPIVOT keyword I can get statistics on different types of contracts.

    My table has these columns:
    ContractNumber int (Primary Key)
    contractXML xml

    My XML looks something like like this, and is stored in a column of type XML:

    <Contract>
      <Customer>
      ...
      </Customer>

      <Order>
        <OrderItem>
          <Name>Product1</Name>
          <Price>123.00</Price>
        </OrderItem>
        <OrderItem>
          <Name>Product1</Name>
          <Price>123.00</Price>
        </OrderItem>
        <OrderItem>
          <Name>Product3</Name>
          <Price>13.00</Price>
        </OrderItem>
        <OrderItem>
          <Name>Product2</Name>
          <Price>23.00</Price>
        </OrderItem>
        <OrderItem>
          <Name>Product1</Name>
          <Price>123.00</Price>
        </OrderItem>
      </Order>
    </Contract>

    To get a table with a max of 5 OrderItems as columns, I can use this query:

        SELECT
          ContractNumber,
          contractXML.value('(/Contract/Order/OrderItem/Name)[1]','varchar(50)') AS Product1,
          contractXML.value('(/Contract/Order/OrderItem/Name)[2]','varchar(50)') AS Product2,
          contractXML.value('(/Contract/Order/OrderItem/Name)[3]','varchar(50)') AS Product3,
          contractXML.value('(/Contract/Order/OrderItem/Name)[4]','varchar(50)') AS Product4,
          contractXML.value('(/Contract/Order/OrderItem/Name)[5]','varchar(50)') AS Product5
        FROM Contract

     

    This is nice, but what if I want to get the number of each product sold? The answer is that I can use the UNPIVOT operator!
    Something like this will do it:

    SELECT Name, COUNT(*) AS [Count] FROM
    (
        SELECT
            ContractNumber, col, Name
        FROM
        (SELECT
        ContractNumber,
        [col1] = contractXML.value('(/Contract/Order/OrderItem/Name)[1]','varchar(50)'),
        [col2] = contractXML.value('(/Contract/Order/OrderItem/Name)[2]','varchar(50)'),
        [col3] = contractXML.value('(/Contract/Order/OrderItem/Name)[3]','varchar(50)'),
        [col4] = contractXML.value('(/Contract/Order/OrderItem/Name)[4]','varchar(50)'),
        [col5] = contractXML.value('(/Contract/Order/OrderItem/Name)[5]','varchar(50)')
        FROM Contract) col
        UNPIVOT(
            Name
            FOR col
            IN ([col1],[col2],[col3],[col4],[col5])
        ) AS unpvt
    ) AS T
    GROUP BY PackageName

    The UNPIVOT operator gives the values in the 5 columns as 1 column.

    If I had only the 1 row in my Contract table from the example above, the result would be:

    Name Count
    Product1 3
    Product2 1
    Product3 1

    This is a simple example, and it has a max number of ordered products per contract of 5. Could maybe be extended.

    If you want a table with the counts for the different products as columns, then something like this would do the job:

    SELECT
       SUM(contractXML.value('count(/Contract/Order/OrderItem[Name="Product1"])','int')) AS Product1,
       SUM(contractXML.value('count(/Contract/Order/OrderItem[Name="Product2"])','int')) AS Product2,
       SUM(contractXML.value('count(/Contract/Order/OrderItem[Name="Product3"])','int')) AS Product3
    FROM Contract

    This would give this result:

    Product1 Product2 Product3
    3 1 1

    And we could of course UNPIVOT this result too:

    SELECT
       ProcuctCount
    FROM
    (SELECT
       SUM(contractXML.value('count(/Contract/Order/OrderItem[Name="Product1"])','int')) AS Product1,
       SUM(contractXML.value('count(/Contract/Order/OrderItem[Name="Product2"])','int')) AS Product2,
       SUM(contractXML.value('count(/Contract/Order/OrderItem[Name="Product3"])','int')) AS Product3
    FROM Contract) cols
    UNPIVOT(
       ProductCount
       FOR cols IN (Product1, Product2, Product3)
    ) AS unpvt

    This should give a table like this:

    ProductCount
    3
    1
    1

    2008-03-03

    Apache Leap Year Bug

    Seems Apache (Web Server) has some rather embarrassing problems with leap years: http://blogs.lodgon.com/johan/Leap_year_issues_in_apache_commonsnet
    https://issues.apache.org/jira/browse/NET-188

    2008-02-12

    Gøran's blog

    I see that this guy, who was a presenter at MSDN Live in Oslo yesterday, has some good links and stuff relating to WPF and hopefully soon something on MVC (Model-View-Controller): http://blog.goeran.no/CategoryView,category,Presentation.aspx

    2008-02-07

    Understanding "login failed" (Error 18456) error messages in SQL Server 2005

    This blog entry explains how to read the "login failed" error message for SQL Server 2005. The messages can be very cryptic, like for instance "Error: 18456, Severity: 14, State: 8. It is the "State" part that tells you the reason the login failed.

    2007-12-14

    Windows Workflow Foundation Links

    This article by Don Box and Dharma Shukla should be good: Simplify Development With The Declarative Model Of Windows Workflow Foundation

    The most trivial and useless WF application, to get newcomers started: http://www.codeproject.com/KB/WF/HelloWF.aspx

    Jump start WF: http://www.codeproject.com/KB/WF/JumpStartWF.aspx

    2007-12-13

    Windows Live Writer

    Blogging just became easier. Using the Windows Live Writer it's pretty easy to make blog entries.

    2007-10-11

    Developing Enhanced Web Experiences with Microsoft® ASP.NET AJAX Extensions

    https://www.microsoftelearning.com/eLearning/offerDetail.aspx?offerPriceId=117972
    Intro to Continuous Integration with VS2008

    This should be interesting:
    http://blogs.msdn.com/buckh/archive/2007/08/14/tfs-2008-a-basic-guide-to-team-build-2008.aspx

    2007-09-27

    Comparison of different versions of SQL Server 2005 features

    Needed to know if SQL Server Express Edition supports indexed views, and found an article on the Microsoft Web Site. Uh-oh... computer says NO!

    2007-07-27

    CustomValidator dependent on multiple controls

    This article describes how to validate 2 or more controls to see if at least 1 of them has content.

    2007-05-29

    Microsoft Office XP Resource Kit downloads

    Useful stuff for MS Office Developers.

    2007-05-09

    The underlying connection was closed: Unable to connect to the remote server.

    This error sometimes occurs when consuming webservices through a proxy.

    2007-05-04

    Load Balancing / EPiServer

    Just putting in a few links so I won't loose them:

    How to configure a Windows Server 2003 Load Balancing cluster:
    Web Farming with the Network Load Balancing Service in Windows Server 2003

    EPiServer:
    Configuring the Cache in Multi-Server Scenarios
    Configuring EPiServer Enterprise Edition

    2007-04-12

    Script error on ASP.NET 1.1 pages

    I got an error message on my aspx web page after one of the latest Windows updates:

    Unable to find script library '/aspnet_client/system_web/1_1_4322/WebUIValidation.js'. Try placing this file manually, or reinstall by running 'aspnet_regiis -c'.

    After trying to reinstall the script library, and reinstalling aspnet on my web application, I found a solution by simply adding the following code to my aspx file:


    <script language="javascript" type="text/javascript" src="/aspnet_client/system_web/1_1_4322/WebUIValidation.js"></script>

    Update:
    After I put in the script-tag above in my "master page", I got an other error on pages not having any validation controls, so I had to put in a hidden dummy validator.

    2006-12-04

    Changing Locale of the ASPNET account

    I have a server that has been installed using default language/locale "en-US".

    This becomes a problem with the date format, which is "MM/dd/yyyy" in en-US, while in Norway where I live we use (nb-NO) "dd.MM.yyyy".

    There is also a problem with which character to use as a decimal point and which to use as a thousand marker/separator:
    Norwegian (nb-NO): decimal point is comma (",") , thousand marker is space. Ex: 2 345,67
    US English (en-US): decimal point is dot ("."), thousand marker is comma. Ex: 2,345.67

    So I need a way to set the locale that the ASPNET account is using.

    There are several ways. You can set this in the web.config file:


    <system.web>
    <globalization
    culture="nb-NO"
    uiCulture="nb-NO" />
    </system.web>


    You can also set it in the users session, by using the Session_Start event handler:


    protected void Session_Start(object sender, EventArgs e)
    {
    this.Session.LCID = 1044;
    }


    If you want to change the default settings of the ASPNET account (and you have the guts), you could go in and change the settings in the registry.

    NB! It may be risky to change settings in the registry. The author of this blog is not responsible for any damage that may be caused by doing so.

    Anyway here it is, change the settings under the following key:

    HKEY_USERS\S-1-5-20\Control Panel\International

    Here you can see settings for number formats, date formats languages etc for the user. I have as of now NOT TESTED THIS, but the key for the ASPNET user should according to a news group be S-1-5-20.

    Good luck!