Microsoft Most Valuable Professional

Chris Pietschmann

An MVP From Wisconsin

LINQ to JavaScript: Update Release v1.01 With More Functionality

Today, I put out v1.01 update release to the LINQ to JavaScript (JSLINQ) Project. This update adds even more LINQ functionality; to view a list of what't been added go here.

I'm currently working on adding some cool things to JSLINQ that will make their way into the next couple releases. Among these are a small JSLINQ Interactive SDK that will make its way into the next release, and some performance enhancements that Brennan Stehling suggested.

If you have any suggestions for this project, please let me know, please post them to the Discussion Board or Issue Tracker.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General
Posted by crpietschmann on Wednesday, January 30, 2008 5:44 PM
Permalink | Comments (0) | Post RSSRSS comment feed


LINQ to JavaScript (JSLINQ) Open Source Project Launched!

I know LINQ is still rather fresh to everyone yet, and you may not have really used it much, but I just started a new Open Source project called "LINQ to JavaScript". Or, JSLINQ for short. This project brings the ease of querying data collections down to the JavaScript world.

Here are some simple examples of using LINQ to JavaScript:

var myList = [
{FirstName:
"Chris",LastName:"Pearson"},
{FirstName:
"Kate",LastName:"Johnson"},
{FirstName:
"Josh",LastName:"Sutherland"},
{FirstName:
"John",LastName:"Ronald"},
{FirstName:
"Steve",LastName:"Pinkerton"}
];

// Select some data by passing in the clauses as Strings
var test = From(myList).
                Where(
"item.FirstName == 'Chris'").
                OrderBy(
"item.FirstName").
                Select(
"item.FirstName");

// Select some data by passing in the clauses as Methods
var test2 = From(myList).
                Where(
function(item){return item.FirstName == 'Chris';}).
                OrderBy(
function(item){return item.FirstName}).
                Select(
function(item){return item.FirstName});

// You can also mix the two
var test3 = From(myList).
                Where(
function(item){return item.FirstName == 'Chris';}).
                OrderBy(
"item.FirstName").
                Select(
"item.FirstName");

As you can see from the above examples JSLINQ supports two methods of defining the operator clauses:

1) You can pass in a string representation of the clause that will get evaluated to return the desired data.

2) You can pass in a method that will get evaluated to return the desired data.

By supporting both of these methods we are able to support two different, easy to write, yet powerful methods of querying any data you may have within JavaScript.

Go check out LINQ to JavaScript here, and download the source!

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General
Posted by crpietschmann on Thursday, January 24, 2008 3:00 PM
Permalink | Comments (0) | Post RSSRSS comment feed


Virtual Earth: Dynamically Load InfoBox Using ASP.NET AJAX

Loading alot of pushpins on the map can slow down your page in two ways: 1) Page load times can be slowed down, and 2) loading pushpins via ajax can be slow. To improve the performance (as in download and database query times) of loading pushpins on the map, you can load the Pushpin Shapes Title and Description on the fly. This allows you to only load the Pushpins Title and Description as it's needed, thus reducing the amount of data you need to send down to the client when initially loading your pushpins.

Dynamically Load InfoBox Title and Description using ASP.NET AJAX

Step 1: When adding Pushpins to the map, use the following format when setting thier Titles: "LOAD:{0}". Replace the "{0}" with a unique ID representing that Pushpin.

var s = new VEShape(VEShapeType.Pushpin, map.GetCenter());
s.Title =
"LOAD:15";
map.AddShape(s);

Step 2: Create the GetInfoBoxData Page Method in the page that we'll call using Ajax. Also create a simple InfoBoxData class in the page; we'll use this class to more easily pass both the Title and Description down to the client.

[WebMethod]
public static InfoBoxData GetInfoBoxData(int id)
{
    // Pass back the InfoBoxData
    InfoBoxData data = new InfoBoxData();
    data.Title =
"Item " + id.ToString();
    // Get the HTML to be displayed within the Description field
    data.Description = ViewManager.RenderView("~/App_Views/InfoBoxDescription.ascx", id);
    return data;
}

Step 3: Add the ViewManager class to the site's App_Code folder. This class will be used within the GetInfoBoxData Page Method to render the Description from a UserControl Template. This class was written by Scott Guthrie in his post titled "Tip/Trick: Cool UI Templating Technique to use with ASP.NET AJAX for non-UpdatePanel scenarios", and it works perfect in this scenario.

public class ViewManager
{
    public static string RenderView(string path)
    {
        return RenderView(path, null);
    }
    public static string RenderView(string path, object data)
    {
        Page pageHolder = new Page();
        UserControl viewControl = (UserControl)pageHolder.LoadControl(path);
        if (data != null)
        {
            Type viewControlType = viewControl.GetType();
            FieldInfo field = viewControlType.GetField("Data");
            if (field != null)
            {
                field.SetValue(viewControl, data);
            }
            else
            {
                throw new Exception("View file: " + path + " does not have a public Data property");
            }
        }
        pageHolder.Controls.Add(viewControl);
        StringWriter output = new StringWriter();
        HttpContext.Current.Server.Execute(pageHolder, output, false);
        return output.ToString();
    }
}

Step 4: Create our InfoBoxDescription UserControl that the GetInfoBoxData Page Method will use as a template for rendering the Description.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="InfoBoxDescription.ascx.cs" Inherits="App_Views_InfoBoxDescription" %>
This is the description for
<strong>Item <%=this.Data.ToString()%></strong>.<br />
This description was generated dynamically using a UserControl.

public partial class App_Views_InfoBoxDescription : System.Web.UI.UserControl
{
    public int Data;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

Step 5:  Attach a JavaScript method to the VE Maps OnMouseMove event, just after the code that instantiates the map.

map.AttachEvent("onmousemove", MapMouseMove);

Step 6: Write code in the OnMouseMove event handler to fire off the GetInfoBoxData Page Method to load the Shapes Title and Description.

function MapMouseMove(e)
{
    if (e.elementID != null)
    {
        var shape = map.GetShapeByID(e.elementID);

        // Check if the Shapes been loaded already
        if (shape.GetTitle().indexOf("LOAD:") != -1)
        {
            // Get our ID for the Shape from within the Shapes Title
            var id = parseInt(shape.GetTitle().substring(5));

            // Set the Shape to display a loading message
            shape.SetTitle("Loading...");

            // Fire off the loading of the InfoBox Data
            PageMethods.GetInfoBoxData(id, /* <-- Pass the WebMethod its parameters */
                InfoBoxDataLoaded, /* <-- The callback method that gets called when the Page Method call Succeeds */
                InfoBoxDataLoadError, /* <-- The callback method that gets called if the Page Method Fails */
                shape /* <-- Pass the Shape as our Context value to the callback method */
            );
        }
    }
}

Step 7: Add our success callback method, that the call to GetInfoBoxData will call once the data has been recieved in the client.

function InfoBoxDataLoaded(result, context, methodName)
{
    var shape = context;
    // Set the Shapes new Title and Description
    shape.SetTitle(result.Title);
    shape.SetDescription(result.Description);
    // Re-Show the InfoBox so the new Title and Description are automatically displayed
    map.ShowInfoBox(shape);
}

Step 8: Add our failure callback method, that the call to GetInfoBoxData will call if it fails.

function InfoBoxDataLoadError(error)
{
    alert(
"Error Occurred Loading InfoBox Data\n" + error.get_message());
}

Conclusion

You'll no longer need to pass the full Title and Description for every Pushpin Shape you plot using this technique. You also be able to save bandwidth, and improve load times in your Virtual Earth implementations.

Download Full Code For This Article Here

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Virtual Earth | asp.net
Posted by crpietschmann on Thursday, January 24, 2008 12:13 PM
Permalink | Comments (0) | Post RSSRSS comment feed


Getting Started with Virtual Earth and ASP.NET AJAX

About a month ago, I wrote an article titled "Virtual Earth: Getting Started - Adding a basic Map to a page". In that article I explained the basics of using Virtual Earth with plain HTML and JavaScript. This time I'm going to explain the basics of using Virtual Earth with ASP.NET AJAX.

Virtual Earth and ASP.NET AJAX

Step 1: Create a new ASP.NET AJAX Web Site in Visual Studio 2005, or just an ASP.NET Web Site in Visual Studio 2008.

Step 2: Open up the Default.aspx page.

Step 3: Add a ScriptManager to the page.

[code:html]
<asp:ScriptManager runat="server" ID="ScriptManager1"></asp:ScriptManager>
[/code]

Step 4: Tell the ScriptManager to load the Virtual Earth API JavaScript file into the page.

[code:html]
<asp:ScriptManager runat="server" ID="ScriptManager1">
    <Scripts>
        <asp:ScriptReference Path="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6" />
    </Scripts>
</asp:ScriptManager>
[/code]

Step 5: Add a DIV to the page below the ScriptManager that will be the host for our Virtual Earth Map.

[code:html]
<div id="myMap" style="position:relative; width:600px; height:400px;"></div>
[/code]

Step 6: Add a JavaScript method to the page that contains code for instantiating the map.

[code:html]
<script type="text/javascript">
    var map = null;


    function LoadMap()
    {
        map = new VEMap("myMap");
        map.LoadMap(new VELatLong(47.6, -122.33), 10, VEMapStyle.Road);
    }
</script>
[/code]

Step 7: Add a line of JavaScript within the script block that attaches the LoadMap method to the application's load event. With this in place the map will get loaded once the asp.net ajax application has finished loading within the browser.

Sys.Application.add_load(LoadMap);

Step 8: Run the page and you'll have a basic Virtual Earth Map on it.

Complete Code For This Article

Default.aspx

[code:html]
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    <asp:ScriptManager runat="server" ID="ScriptManager1">
        <Scripts>
            <asp:ScriptReference Path="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6" />
        </Scripts>
    </asp:ScriptManager>
   
    <div id="myMap" style="position:relative; width:600px; height:400px;"></div>
   
    <script type="text/javascript">
        var map = null;
       
        function LoadMap()
        {
            map = new VEMap("myMap");
            map.LoadMap(new VELatLong(47.6, -122.33), 10, VEMapStyle.Road);
        }
       
        // Attach our LoadMap method to get executed
        // when the Application has finished loading.
        Sys.Application.add_load(LoadMap);
    </script>
   
    </div>
    </form>
</body>
</html>
[/code]

Conclusion

If you compare this article with the "Virtual Earth: Getting Started - Adding a basic Map to a page" article, you'll see that there aren't very many differences in how you place a Virtual Earth Map on the page. The only big differences are: 1) you can use the ScriptManager in ASP.NET AJAX to include the VE API script in the page, and 2) ASP.NET AJAX makes it easier to attach a method to get executed when the page/application has loaded.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by crpietschmann on Thursday, January 24, 2008 3:40 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Introduction to LINQ

What is LINQ?

LINQ (Language INtegrated Query) is more than just a new method of embedding SQL queries within code. It allows to to perform Strongly Typed queries on any kind of data, just as long as the collection of data implements the IEnumerable interface.

The most important part is "Language Integrated". This allows you to more easily write queries in C# 3.0 and VB 9.0 such as:

IEnumerable<Person> filterExample1 = from Person in people
                                                               
where Person.FirstName.ToUpperInvariant().StartsWith("J")
                                                                select Person;

Instead of:

IEnumerable<Person> filterExample2 = people
                                                            .Where(p => p.FirstName.ToUpperInvariant().StartsWith(
"J"))
                                                            .Select(p => p);

As you can see the second option takes a little longer to write and isn't quite as easy to read as the first option or a standard SQL query. It essentially allows us to query our data in a SQL-like fashion that we're already familiar with.

The second important part of LINQ (and probably just as important) is since all you query code is written in .NET, you get the benefit of things being Strongly Types, and the compiler type checking the code at compile time. You'll no longer get strange type exceptions at run-time with LINQ that you would traditionally get if you used SQL string within your code.

There's more than one type of LINQ?

Yes, but don't get scared away just yet. The different types of LINQ are for querying different types of data. The differnet types of LINQ are as follows:

  • LINQ to Objects - This type is geared towards working with collections of Objects, hence the name.
  • LINQ to SQL - This type is geared towards working with data from a database.
  • LINQ to XML - This type is geared toward working with data in XML documents.

In the rest of this article we'll be using LINQ to Objects.

Basic Query Syntax

First lets look at the following example; which filters out all the Person objects with a FirstName that starts with the letter "J":

IEnumerable<Person> filterExample1 = from Person in people
                                                                   
where Person.FirstName.ToUpperInvariant().StartsWith("J")
                                                                    select Person;

First we declare the collection of data we're going to query from using the "from" operator, "from Person in people". "people" is our collection that inherits from IEnumerable<T> and "Person" is type of object that collection contains.

Second we define any query criteria using the "where" operator. You can define as many where clauses as necessary.

And lastly, we declare the data we're going to select using the "select" operator.

One thing to note when using LINQ: you must define the data to select Last, as compared to First with the SQL language.

Other Simple LINQ Examples

"orderby" Operator: The "orderby" operator allows you to sort your query results.

IEnumerable<Person> orderByAge = from Person in people
                                                                    orderby Person.Age
                                                                    select Person;

"let" Operator: The "let" operator allows you to declare a new variable within the scope of the query. This new variable can only be used by query clauses that are declared after the use of the "let" operator.

IEnumerable<Person> letExample1 = from Person in people
                                                               
let firstname = Person.FirstName.ToUpperInvariant()
                                                                where firstname.StartsWith("J")
                                                                select Person;

Select Distinct Items: You can use the Distinct() method to grab just the distinct items in the collection.

IEnumerable<String> distinctExample2 = (from Person in people
                                                                      
select Person.FirstName).Distinct();

Conclusion

As you can see, LINQ is rather simple to use the basics of. However, it is rather involved and will definately take some time to master.

For further reading:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General
Posted by crpietschmann on Thursday, January 24, 2008 2:00 AM
Permalink | Comments (1) | Post RSSRSS comment feed

2008 Launch Event and Free Software

On February 27th in Los Angeles, CA, Microsoft is kicking off a series of "HEROES happen {here}" launch events nationwide. These are the official launch events for Windows Server 2008, Visual Studio 2008, and SQL Server 2008. And, one of the best parts is everyone that takes part in one of the events will be taking home a promotional kit with versions of all three products.

Since the Milwaukee event isn't until May 8th, I've registered for the Chicago event on March 11th. I don't want to wait that long!

For More Information

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General
Posted by crpietschmann on Monday, January 21, 2008 7:39 PM
Permalink | Comments (0) | Post RSSRSS comment feed

QBasic was my First Programming Language

Recently, I got to thinking about my beginning of programming, and the Basic language. So, I thought I'd explain my early history with Basic a little bit.

Basic was Easy

My first programming language was QBasic. The reason I started learning QBasic was for the following reasons:

  1. QBasic came for Free on the Windows 95 CD-ROM
  2. There were more help sites on the internet dedicated to QB than any other language at the time.
  3. There weren't many resources on C++ back in the day (about 1996), even though it was the most used programming language.

Also, I was able to easily read and play with other peoples code to learn how to do things. I spent hours breaking code I found online, just to learn what different things did. I never had a book on QBasic, and I read very few tutorials. I actually learned mostly from reading and breaking other peoples code.

QBasic was Powerful

Basic was a very powerful language. I actually created a couple really need programs back then, along with a bunch of other ones not as noteworthy:

1) I created a QBasic application that allowed you to connect two computers over the modem and chat via text and share files. I named the program Tele-Chat and submitted it to a QB help site and actually won an award for it.

2)I created a DOS Program Manager app that made use of the mouse to give a nice UI for launching applications rather than using the command line. This was my first Event Driven application; I wrote this before I even saw what Visual Basic was. When I wrote it, I just wanted to make an app that worked more like Windows 3.1. The code snippet that I used to enable the use of the Mouse was actually a bit of Assembly that was executed from within QB that I copied from some help site somewhere.

3) I also started writing an RPG, named The Unknown World, that was sort of an original Zelda style game in QBasic. It made use of bit masking, and timers. It was pretty cool. The timer was essentially an infinite loop that looked for keys to be pressed to do stuff like move the character. I had a friend helping me on the graphics a little bit, and the game was looking pretty cool.

However, development slowed when I hit the file site limit in QBasic. If I remember correctly you could only have a code file of 64K or smaller. So to get around this limitation that crippled my game, I just created seperate EXE's for different parts of the game (like going into a building) that I ran at those moments. Then it would write to a TXT file what happened in the room, and when it was done executing the main app would read that TXT file and take the appropriate action.

However, The Unkown World was never finished as I lost interest in it. I was also moving on to VB at the time.

Conclusion

I, just as many others, found QBasic to be the gateway to becoming a programmer and software developer. I'll never forget those days of spending hours after school playing around with the wonder that was this big white IBM 486 PC on my fathers desk.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General
Posted by crpietschmann on Monday, January 21, 2008 4:20 PM
Permalink | Comments (0) | Post RSSRSS comment feed

JavaScript int.TryParse Equivalent

One of the most handy methods in .NET is the int.TryParse method. It makes it really convenient when evaluating a string value as an integer. But, JavaScript has no equivalent so you need to do your own evaluation every time.

Here's a simple JavaScript method I wrote that takes the work out of evaluating a string to an integer:

The first parameter of the TryParseInt method is the string you want to evaluate, and the second parameter is the default value to return if the string cannot be evaluated to an integer.

Here are some example usages:

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General
Posted by crpietschmann on Monday, January 14, 2008 9:47 PM
Permalink | Comments (1) | Post RSSRSS comment feed

DotNetKicks is 2 years old, today! Way to go!

The DotNetKicks site is 2 years old today. Way to go! Gavin Joyce started it, and now two years ago and alot of community contribution the site definately the place to find any resource you need on anything MS .NET related.

What is DotNetKicks.com?

DotNetKicks.com is a community based news site edited by our members. It specialises in .NET development techniques, technologies and tools including ASP.NET, C#, VB.NET, C++, Visual Studio, SubSonic, Open Source, SQL Server, Silverlight & Mono.

Individual users of the site submit and review stories, the most popular of which make it to the homepage. Users are encouraged to 'kick' stories that they would like to appear on the homepage. If a story receives enough kicks, it will be promoted.

It's also an Open Source project

That right, DotNetKicks is an open-source project. You can take the code that runs DotNetKicks and create your own social news site.

I've been using DotNetKicks for almost the entire 2 years

I haven't setup my own site, but I have been using DotNetKicks since March 2006. So, I've been a contributor/user almost the entire time they've been live, and I'm not leaving the DotNetKicks community anytime soon.

Congratulations to everyone involved, especially Gavin Joyce! Everyone has done an awesome job!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General
Posted by crpietschmann on Tuesday, January 08, 2008 9:43 PM
Permalink | Comments (0) | Post RSSRSS comment feed

About the author

I'm Chris Pietschmann, go to the About Me page to learn more about me.

Search

Sponsors

Web.Maps.VE - ASP.NET AJAX Virtual Earth Mapping Server Control

Recent comments

Disclaimer


This work is licensed under a Creative Commons Attribution 3.0 United States License, unless explicitly stated otherwise within the posted content.
© Copyright 2004 - 2008 Chris Pietschmann