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;