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