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!

2006-09-27

ADODB serialization

Found a simple but cool way to serialize an ADODB Recordset without converting to DataSet on CodeProject.

2006-08-14

Security Developer Center: Security Tips: Defend Your Code with Top Ten Security Tips Every Developer Must Know

Not sure if I have bookmarked this before. Well, better safe than sorry...

2006-06-22

Build your own cryptographically safe server/client protocol - The Code Project - Internet & Network

Good article that explains quite a bit about how cryptography works.

2006-06-15

Some Cool Tips for .NET - The Code Project - C# Controls

Nice to know info on how to get information about windows and other stuff.

2006-05-30

SQL Server Monitoring in 8 Steps: Lessons From the Field

How to get a quick status of the server while on-site.

2006-05-23

Free JavaScript DHTML Website Menus, Cross Browser Popup Web Menu

Nice, free Javascript menus.
The Soul of a Virtual Machine : Sysprepping a virtual machine

Description of how to sysprep a VPC. Useful stuff.

2006-04-04

HttpSecureCookie, A Way to Encrypt Cookies with ASP.NET 2.0 - The Code Project - ASP.NET

This article describes how to encrypt cookies in .NET 2.0.

2006-04-03

The 46 Best-ever Freeware Utilities

This is a nice page with lots of free software links. Among others, web browsers and antivirus programs.
Auditing Web Site Authentication, Part One

Every web developer should read this. Excellent!
An introduction to Web Service Security using WSE - Part I - The Code Project - C++ Web Services

Some big players as Microsoft and IBM built a group that dealed with the security problem (of Web Services), finally offering several specifications. The most important, and foundation of the others, is Web Service-Security (WS-Security or WSS).

2006-03-29

SSH : Support : Cryptography A-Z

Site with a lot of information on cryptography, and different algorithms.
Visual Studio 2005: Visual Studio 2005 Code Snippets

This is very cool! Nice and free collection of code snippets from Microsoft, ready for pasting into your application source.

2006-03-28

Server-Side Asynchronous Methods for ASP.NET and WinFX - The Code Project - C# WebServices

This article describes how to make asychronous calls to a web service. This is useful when the web service has to perform some task that takes a while to complete before returning the result to the client. By making an asynchronous call, the thread of the calling process can go back into the pool and be useful for other purposes while waiting for the response.

2006-03-27

ITavisen.no | Nettet på: en helt ny måte

This article in Norwegian gives a few tips on starting out with Ajax (Asyncronous Javascript and XML).

2006-03-24

WebService Connection problems

Quote from a newsgroup (slightly modified):
"If a website (or a webservice) calls a webservice on the same server, then there is no limit on outgoing connections on the Framework. Due to this, the number of outgoing connections to the ASMX page will be huge, and for each connect that takes place, one wildcard TCP port gets used. Since there is a limit of 5000 wildcard TCP ports on the OS, pretty soon, after 5000 or so socket.Connects(), they will start failing with "unable to connect exceptions".

If the authentication is set to NTLM, then you will run into this problem sooner. This is because NTLM uses one extra connection, and after each successful request, that connection is torn down. If you are running into this, try setting "UnsafeAuthenticatedConnectionSharing=true" on the underlying HttpWebRequest
of the client."

A web service client has in .NET by default a limit of 2 connections. You can adjust this limit by putting the following into the web.config file of the client web (not sure about winforms clients, but probably you can put the same into the config file here as well):

<system.net>
<connectionmanagement>
<add maxconnection="40" address="*">
</connectionmanagement>
</system.net>
Solving "The underlying connection was closed: An unexpected error occurred on a send." (Webservices)

Jan Thielen (MVP) gives a solution to the problem of sporadic errors of type "The underlying connection was closed".

In essence, you need to add the following code to your Webreference's Reference.cs file:


protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
System.Net.HttpWebRequest webRequest =
(System.Net.HttpWebRequest) base.GetWebRequest(uri);
webRequest.KeepAlive = false; return webRequest;
}

2006-03-20

Caring for your introvert

This article explains why introverts are the way they are, so that maybe extroverts can understand them better.

2006-03-06

Code Generation with Codesmith

Codesmith is an excellent tool for generating general code, like for instance cargos. You don't always have to type all the boring code. Codesmith can do some of the tedious work!
Sam Gentile : No More VSS, Its Subversion

Visual Sourcesafe or as it is now known Team System is not so stable it seems. This to a degree that makes Same Gentile refer to it under the name "Unsafe" (as opposed to its real name "SourceSafe"). His team is now going for the open-source freeware Subversion source code versioning system.

2006-03-03

List of .NET 2.0 and C# 2.0 new features - The Code Project - Book Chapters

Very useful list of new features in .NET 2.0 and C" 2.0.
Ajax (programming) - Wikipedia, the free encyclopedia

Ajax is a hot buzzword these days (Asynchronous Javascript And Xml). It is a technique for making web GUIs that look more like windows forms applications (less flicker, less postback) because more operations are performed client-side.
Bamboo.Prevalence - a .NET object prevalence engine

An alternate to storing business objects in a database. Now that 64 bit CPU's are coming more and more, and they can handle much more RAM, this is probably something for now and the future. 3000 times faster than mySQL!

This is how it works:
1) All business objects are stored in RAM. 2) Once in a while a snapshot of all business objects is serialised to disk. 3) All operations on objects are stored in a log.

So what if the server crashes?
1) Restore the last snapshot.
2) Replay all actions from log.
A lot like the MS SQL Server backup / Transaction Log bacup.

2006-02-15

Request.ServerVariables("HTTP_REFERER") - What is going on?

NIS by default blocks the header "HTTP_REFERER" to be sent from the browser to the server. If your web application is depending on this servervariable, and your clients are using NIS, then do the following:

NIS:
- Privacy control - configure
- Advanced button
- Global settings tab
- "Information about visited sites"

If blocked (this appears to be the default) then HTTP-REFERER is wiped out. Change this option to allow the header to be sent.

2006-02-10

.NET Tools: Ten Must-Have Tools Every Developer Should Download Now -- MSDN Magazine, July 2004

You cannot expect to build a first-class application unless you use the best available tools. Besides well-known tools such as Visual Studio® .NET, there are a multitude of small, lesser-known tools available from the .NET community. In this article, James Avery describes some of the best free tools available today that target .NET development.

2006-02-06

FuzzyEnumParse

This function takes an Enum type and a text representing the value of the enum, and if the Enum has a field with a name contained in the text (enumText), then it returns that value.

For use when for instance the database field to parse from has been extended somewhat... Modify to suit your needs!


private object FuzzyEnumParse(System.Type type, string enumText)
{
System.Reflection.FieldInfo[] fis = type.GetFields();
foreach(System.Reflection.FieldInfo fi in fis)
{
if(fi.Name!="value__")
{
object obj=fi.GetValue(null);
if(enumText.IndexOf(obj.ToString())>-1)
{
return obj;
}
}
}
return null;
}

2006-02-01

Serialising doesn't work for read-only properties in webservices

I have been puzzled by the behavior of my webservice. I have a couple of properties in an object that is sent as a parameter to the webservice. Since these properties are not assigned directly by any code, I didn't implement a "set" method for the properies. (As it turns out: Bad mistake!)

What happened was that the values were set in the client to "true", but when the object arrived inside the webservice, the values were suddenly "false".

It turns out, if you don't implement both "get" and "set" for a property, it will not be serialised.

2006-01-19

#2413 : Why do I get non-database-related 80004005 errors?: "Request object, ASP 0104
Operation not allowed"

I got this error at a customer's after they upgraded their web servers to Windows Server 2003. The error appears when trying to upload files through the web. Turns out there is a setting in the metabase.xml file (located in the Windows\System32\inetsrv directory) called AspMaxRequestEntityAllowed, that sets the maximum filesize allowed to be uploaded. This is set very low as a default, to only 204 Kb. In Windows 2000 Server you could upload files much larger (well at or above 1 Meg anyway, I believe).

2006-01-18

Best Practices for Microsoft Business Intelligence : Checks used for remoting a query to the server

Describes different reasons why a query can not be executed on the server.

2006-01-13

Discworld Quotes

A page with lots of cool quotes from the Discworld series (Terry Prattchett).

My favorite (from "Thief of Time):
If you put a large switch in some cave somewhere, with a sign on it saying 'End-Of-The-World Switch. PLEASE DO NOT TOUCH', the paint wouldn't even have time to dry.

Another good one:
"I'll tell you, the day someone pulls the plug out of the bottom of the universe, the chain will lead all the way to Ankh-Morpork and some bugger saying, 'I just wanted to see what would happen.'"
OleDbException E_FAIL(0x80004005)

Got this message when I was trying to connect to Analysis Services:
Exception: System.Data.OleDb.OleDbException
Message: No error information available: E_FAIL(0x80004005).

Looks like the most common explanation is that one of the field names in the query is a SQL reserved word, like for instance "Name", "Size" or "Read". If you use bracketed field names this should not be a problem.
LinkD

A little comparation of the subst command and the LinkD tool. From Craig Andera's blog. Craig also published the now legendary "The last config section handler I'll ever need".

2006-01-02

MSDN TV: Special Holiday Episode III: Connecting People, Programs and Devices Using WinFX: "Special Holiday Episode III: Connecting People, Programs and Devices Using WinFX"

Don Box and Chris Anderson show how to build real applications that leverage the major components in WinFX. With rich UI, robust communication, and workflow control, they build an application that integrates with various devices laying around Don's home to demonstrate how to use WinFX together.