• <dw:daniel_walzenbach runat="server" />

    How to enable remote connections in SQL Server 2008?

    • 108 Comments

    You experience the following error message:

    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
    SQL Server 2008: The server was not found or was not accessible.

    How to solve this issue?

    There are a couple of things that might be going on here… (All of the following configurations are made on the computer running your SQL Server 2008 instance)

    Allow remote connections to this server

    The first thing you want to check is if Remote Connections are enabled on your SQL Server database. In SQL Server 2008 you do this by opening SQL Server 2008 Management Studio, connect to the server in question, right click the server…

    SQL Server 2008: Server Properties

    … and open the Server Properties.

    SQL Server 2008: Server Properties - Connections

    Navigate to Connections and ensure that Allow remote connections to this server is checked. Check if this solves the problem. If it does, here you go, continue with whatever you were doing and have a nice day.

    Protocols for MSSQLServer

    If you’re still running in issues let’s dig a bit deeper. The next good thing to check is the SQL Server Network Configuration. Open the SQL Server Configuration Manager, unfold the node SQL Server Network Configuration and select Protocols for MSSQLServer (or whatever the name of your SQL Server instance is).

    SQL Server 2008: Protocols for MSSQLServer

    Make sure that TCP/IP is enabled and try again. Even though I hope that this resolved your problems there might still be an issue with…

    The Firewall

    If there is still no communication happening between your computer and the remote SQL Server you most likely need to configure your firewall settings. A good first step is to figure out which port is being used by TCP/IP (and which you need to open in your firewall). You can do this by right clicking TCP/IP and selecting Properties.

    SQL Server 2008: TCP/IP Properties

    Click on the tab IP Addresses and voilà – Port 1433 it is :-) That was easy enough and all there is left to do is to allow inbound TCP/IP traffic on Port 1433 in your firewall. In Windows 7 this works something like this. Open the Control Panel and navigate to Windows Firewall.

    Microsoft Windows 7 Firewall settings

    Click on Advanced Settings on the left hand side and you should see the Windows Firewall with Advanced Security. Select the Inboud Rules on the left hand side and click on New Rule… on the right hand side.

    Microsoft Windows 7 Firewall with Advanced Security

    This opens the New Inbound Rule Wizard which you can use to allow inbound traffic on Port 1433 for TCP/IP (and which is exactly how you configured your SQL Server in the steps above). Just follow the steps outlined below and you should be good :-)

    New Inbound Rule Wizard - Protocols and Ports

    New Inbound Rule Wizard - Protocols and Ports

    New Inbound Rule Wizard - Action

    New Inbound Rule Wizard - Profile

    New Inbound Rule Wizard - Name

    That’s it, success! From here you should be able to access your SQL Server remotely. Enjoy!

    Cheers!

       Daniel

    P.S. There's a good article on msdn on this topic if you're looking for additional information >> Configuring the Windows Firewall to Allow SQL Server Access.

    Update (June 14th, 2010):

     

  • <dw:daniel_walzenbach runat="server" />

    Goodbye Microsoft Germany

    • 19 Comments

    If you follow my blog you might have noticed that I haven’t written anything for quite a while. The reason behind this is that I quitted my job at Microsoft Germany and am moving to Seattle next week. I’m currently sitting in between a gazillion of packing cases with a couple of movers swirling around. After deciding which part of my household will be air freight (Munich > Seattle: 8-10 days) and which part will be sea freight (Munich > Seattle: 10-12 weeks) I’m basically domed to do nothing (giving me the opportunity to blog :-) )! Not that I hadn’t offered my help -  I’m not allowed to pack anything for insurance reasons. Strange feeling to see ones life disappear in a couple of boxes ;-)

    So what’s happening next? I’ll spend my last days in Munich (basically the next two) redecorating my apartment and trying to find a next tenant (not that I didn’t already had someone but it didn’t turned out). Additionally I’m handing over my last possessions and am saying goodbye to my friends and 220V devices ;-)

    See you in Seattle :-) Cheers!

       Daniel

  • <dw:daniel_walzenbach runat="server" />

    Do you know your language? The tiny C# quiz :-)

    • 11 Comments

    Why does double d = (double)((object)1.2F); result in a System.InvalidCastException?

    Polls are open ;-)

    Daniel

  • <dw:daniel_walzenbach runat="server" />

    Ich will es wissen! Was machen wir (als Microsoft) gut, was machen wir schlecht und was sollten wir anders machen?

    • 11 Comments

    Ok. Hier ganz unverblühmt. Der virtuelle Kummerkasten! Ich will es wissen und ich versuche Antworten zu geben warum wir machen was wir machen!

    1. Was machen wir (als Microsoft) gut
    2. was machen wir schlecht und
    3. was sollten wir anders machen?

    Jetzt ist die Gelegenheit mal Frust abzulassen, ein positives Feedback zu geben oder auch konstruktive Kritik zu üben. Und zwar in allen Bereichen! Nicht nur rund um die Softwareentwicklung. Also, los geht's!

    Daniel

  • <dw:daniel_walzenbach runat="server" />

    Unglaublich cooler Physiksimulator (incl. Source Code)! Zuuuuu arg!!!

    • 9 Comments

    In Zusammenarbeit zwischen Microsoft und MIT ist der "Physics Illustrator" entstanden welcher auf YouTube zu sehen ist. :-)
    http://www.youtube.com/watch?v=d7eGypGOlOc

    Als wäre das Video nicht schon cool genug ist der "Physics Illustrator" als kostenloser Download verfügbar :-))
    http://www.microsoft.com/downloads/details.aspx?FamilyID=56347faf-a639-4f3b-9b87-1487fd4b5a53&displaylang=en

    Und da es immer noch etwas besser werden kann stellt Microsoft Research den Quellcode des "Physics Illustrator" zum Download bereit :-)))
    http://research.microsoft.com/research/downloads/Details/aeee3085-a219-47d6-88fc-a2501f00800d/Details.aspx

    Ich bin sprachlos...

    P.S. Wer einen TabletPC sein eigen nennt kann sofort zu spielen anfangen :-))))

  • <dw:daniel_walzenbach runat="server" />

    ASP.NET Ajax TechTalk (Update)

    • 8 Comments

    Vorbei sind die Zeiten grauer, langweiliger Webanwendungen die hauptsächlich aus einer Ansammlung von Texten und Links bestanden. Der aktuelle Trend geht zu interaktiven, reichhaltigen Anwendungen welche die Features und Funktionalitäten traditioneller Desktopanwendungen in einer Webanwendung im Browser zur Verfügung stellen. Ermöglicht wurde dieser Trend u.a. durch ein Programmiermodell welches heute unter dem Namen Ajax (Asynchronous JavaScript and XML) in aller Munde ist und die inzwischen zahlreichen Ajax Frameworks, welche die Entwicklung komplexer Anwendungen deutlich erleichtern.

    Dieser TechTalk gibt einen Überblick über das ASP.NET Ajax Framework von Microsoft. Daniel Walzenbach, Developer Evangelist der Microsoft Deutschland GmbH, vermittelt die Technologien welche Ajax erst ermöglichen, verdeutlicht an vielen Beispielen die Entwicklung von Ajax Anwendungen mit dem ASP.NET Ajax Framework und geht im Anschluss auf Problemstellungen ein, die in „real-world“ Anwendungen auftreten. Gegenstand dieses TechTalks sind weiterhin Themen wie Performance von Ajax Anwendungen und Toolunterstützung.

    Veranstaltungsorte:

    Ort

    Datum

    Veranstaltungsort

    Zur Anmeldung

    Hamburg

    09.01.2008

    Mercure Hamburg City

    Amsinckstr. 53,

    20097 Hamburg

    TechTalk: ASP.NET Ajax

    Berlin

    10.01.2008

    Hotel Spreebogen Berlin

    Alt-Moabit 99,

    10559 Berlin

    TechTalk: ASP.NET Ajax

    Bonn

    15.01.2008

    CommaSoft AG

    Pützchens Chaussee 202-204a,

    53229 Bonn

    (Zugang über Holtorfer Straße)

    TechTalk: ASP.NET Ajax

    Karlsruhe

    21.01.2008

    Dorint Novotel Karlsruhe Kongress

    Festplatz 2,

    76137 Karlsruhe

    TechTalk: ASP.NET Ajax

    München

    24.01.2008

    Hilton Munich Park

    Am Tucherpark 7,

    80538 München

    TechTalk: ASP.NET Ajax

    Bis bald!

    Daniel

  • <dw:daniel_walzenbach runat="server" />

    Geocoding or How to transform a list of addresses into Latitude/Longitude values and display them on a map? Sourcecode included!

    • 8 Comments

    Since I did http://www.woistdaniel.de/ and occasionally talk about Virtual Earth I almost always get asked the same question. Someone has a list of companies/stores/medics/pharmacies/clubs/museums/”u name it” with the address consisting of the street, zip code and the city, wants to display those items on a map and provide additional information for them. Unfortunately I never had a comprehensive reference to point to and therefore decided to write a step by step guide on the above topic on my own ;-)

    Geocode the data

    Let’s get started with some random locations in Munich that should be visualized on a Virtual Earth map and imagine, that we have the data in an excel sheet like this:

    Name Description AddressLine PostalCode PrimaryCity CountryRegion URL
    Haus der Kunst Art museum in Munich with changing exhibitions. Prinzregentenstrasse 1 80538 Munich Germany http://www.hausderkunst.de/
    Deutsches Museum The world's largest museum of technology and science. Museumsinsel 1 80538 Munich Germany http://www.deutsches-museum.de/
    Asamkirche One of the most splendid achievements of Bavarian late Baroque architecture or rococo. Sendlinger Straße 32 80331 Munich Germany http://en.wikipedia.org/wiki/Asamkirche
    Frauenkirche The landmark of Munich Frauenplatz 1 80331 Munich Germany http://www.muenchen.de/Tourismus/Sehenswuerdigkeiten/Muenchen_in_Bildern_neu/Webcam_c/198612/Frauenkirche.html
    Hofbräuhaus Brewery in Munich. No explanation needed ;-) Platzl 9 80331 Munich Germany http://www.hofbraeuhaus.de

    In order to place those items on a map we first have to geocode them which basically is determining the latitude and longitude coordinates for a physical address. While there are multiple possibilities to geocode data we are going to use the Virtual Earth Platform Customer Services since those services allow batch converting of hundreds of thousands of locations at once (972,222 to be exactly => start thinking big ;-) ). To make things even better there is a Virtual Earth Platform Developer Account which allows one to use the aforementioned services free of charge. Sign up here https://mappoint-css.live.com/mwssignup/, validate the confirmation email and that’s it.

    Now that we have a Virtual Earth Platform Developer Account let's go back to our sample data. Geocoding them is as simple as uploading the data to the Virtual Earth Platform Customer Services site as geocoding your data happens automatically. To upload your data the file containing the data has to be either a Microsoft Office Access 2002 or Microsoft Office Access 2003 XML file with an embedded schema or a delimited-field flat file where the first row defines the schema. Valid delimiters are commas, tabs, or pipes ( | ) and only a single delimiter must be used consistently throughout the file.
    Simply create a database like the following containing one table to hold the locations or download the one I used. The column EntityID has to be of Type Long Integer, the Latitude and Longitude column have to be of type Double.

    Fill the table with your data and leave the columns Latitude and Longitude empty. These columns will later be filled automatically by the Virtual Earth Platform Customer Services.

    Now export your data to an xml file by right-clicking on the table in the left and select export >> XML-file. Be sure to include the schema in the xml file on the following dialog and save the file.

    As we now have the location data in a format the Virtual Earth Platform Customer Services can understand, log in to the Virtual Earth Platform Customer Services site and upload the data. Simply click on the "Create" Button in the Data Sources section on the right-hand side, fill out the dialog like this and click Create.

    Your data will now be uploaded and geocoded resulting in this image after a short moment.

    To download the data click the download link in the Data Sources section,

    choose the output format

    and find the downloadable file in the Recent jobs list an instance later.

    Besides the included schema at the top of the file the geocoded data looks like this:

    <dataroot>WoIstDanielConnectionString
          <MapPoint>
                <EntityID>1</EntityID>
                <Name>Haus der Kunst</Name>
                <Description>Art museum in Munich with changing exhibitions.</Description>
                <AddressLine>Prinzregentenstrasse 1</AddressLine>
                <PostalCode>80538</PostalCode>
                <PrimaryCity>Munich</PrimaryCity>
                <CountryRegion>Germany</CountryRegion>
                <URL>http://www.hausderkunst.de/</URL>
                <Latitude>48.143927081912203</Latitude>
                <Longitude>11.5844456484113</Longitude>
                <MatchCode>Good</MatchCode>
                <MatchedMethod>Address</MatchedMethod>
                <MatchedAddress>Prinzregentenstraße 1, 80538 München</MatchedAddress>
          </MapPoint>
          <MapPoint>
                <EntityID>2</EntityID>
                <Name>Deutsches Museum</Name>
                <Description>The world's largest museum of technology and science.</Description>
                <AddressLine>Museumsinsel 1</AddressLine>
                <PostalCode>80538</PostalCode>
                <PrimaryCity>Munich</PrimaryCity>
                <CountryRegion>Germany</CountryRegion>
                <URL>http://www.deutsches-museum.de/</URL>
                <Latitude>48.130676514922399</Latitude>
                <Longitude>11.5836371247683</Longitude>
                <MatchCode>Ambiguous</MatchCode>
                <MatchedMethod>Address</MatchedMethod>
                <MatchedAddress>Museumsinsel 1, 80538 München</MatchedAddress>
          </MapPoint>
         
    ...
          <MapPoint>
                <EntityID>5</EntityID>
                <Name>Hofbräuhaus</Name>
                <Description>Famous Brewery in Munich.</Description>
                <AddressLine>Platzl 9</AddressLine>
                <PostalCode>80331</PostalCode>
                <PrimaryCity>Munich</PrimaryCity>
                <CountryRegion>Germany</CountryRegion>
                <URL>http://www.hofbraeuhaus.de/</URL>
                <Latitude>48.137615987119098</Latitude>
                <Longitude>11.579696959390899</Longitude>
                <MatchCode>Good</MatchCode>
                <MatchedMethod>Address</MatchedMethod>
                <MatchedAddress>Platzl 9, 80331 München</MatchedAddress>
          </MapPoint>
    </dataroot>

    Visualize the geocoded data on a Virtual Earth map

    Lets start with some infrastructure and build a webservice that returns a List(Of Location) which we will use later.

    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    Imports System.ComponentModel

    ' ScriptService >> To allow this Web Service to be called from script, using ASP.NET AJAX.
    <System.Web.Script.Services.ScriptService()> _
    <System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
    <System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
    <ToolboxItem(False)> _
    Public Class Locations
        Inherits System.Web.Services.WebService

        <WebMethod()> _
        Public Function GetLocations() As List(Of Location)
            Dim _xmlLocations = String.Format("{0}App_Data\MapPointOutput.xml", AppDomain.CurrentDomain.BaseDirectory)
            Dim query = From item In XElement.Load(_xmlLocations)...<MapPoint> _
                        Select New Location With {.Name = item.<Name>.Value, _
                                                  .Description = item.<Description>.Value, _
                                                  .MatchedAddress = item.<MatchedAddress>.Value, _
                                                  .URL = item.<URL>.Value, _
                                                  .Latitude = item.<Latitude>.Value.ReplaceDecimalSeparator, _
                                                  .Longitude = item.<Longitude>.Value.ReplaceDecimalSeparator}
            Return query.ToList
        End Function

    End Class

    Public Class Location
        Public Name As String
        Public Description As String
        Public MatchedAddress As String
        Public URL As String
        Public Latitude As Double
        Public Longitude As Double
    End Class

    Public Module Tools
        ''' <summary>
        ''' This tiny function enables to call ReplaceDecimalSeparator on any String Type
        ''' </summary>
        ''' <param name="Value"></param>
        ''' <returns></returns>
        ''' <remarks>Needed to convert a value into a Double. Based on the decimalseparator the conversion from String to Double can sometimes return wrong values.</remarks>
        <Runtime.CompilerServices.Extension()> _
        Public Function ReplaceDecimalSeparator(ByVal Value As String) As Double

            If String.IsNullOrEmpty(Value) Then
                Return 0
            End If

            Return CDbl(Value.Replace(".", Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator))

        End Function

    End Module

    Note that we are using LINQ to XML to query the data we want to show on the map and the use of the extension method ReplaceDecimalSeparator which makes programming much more intuitive. Sweet :-)

    In order to be able to consume this webservice from our website with JavaScript we are using the ASP.NET Ajax Framework, or - to be more specific - the ScriptManager and include a reference to the webservice in the Scripts section of the ScriptManager. We also need to place a <div /> tag on the website to hold the Virtual Earth map. The final result can be seen here:

    <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="ShowLocationsOnVirtualEarth._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>How to show a list of locations on a Virtual Earth map.</title>
        <script src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6" type="text/javascript"></script>

        <script type="text/javascript">

            function pageLoad() {
                // InitializeMap is located in VEMap.js and takes care
                // that the map gets initialized and loads the data
                // afterwards

                InitializeMap();
            }

        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
                <Scripts>
                    <asp:ScriptReference Path="~/JavaScript/VEMap.js" />
                </Scripts>
                <Services>
                    <asp:ServiceReference Path="~/WebServices/Locations.asmx" />
                </Services>
            </asp:ScriptManager>

            <div id='myMap' style="position:absolute; top:0px; left:0px; width:800px; height:600px;"></div>

        </div>
        </form>
    </body>
    </html>

    Additionally some JavaScript is needed to actually draw the locations on the map (This is the file VEMap.js referenced in the above code).

    var map = null;                 // this var holds the VE map

    // Initializes the VE map and calls the method to load the data
    function InitializeMap() {

        // make sure map is initialized
        if (map == null) {
            map = new VEMap('myMap');   // initialize map
            map.LoadMap();              // load it
            map.SetMapStyle('r');       // set the MapStype to "Road"
            map.SetCenter(new VELatLong("48.132241398091125", "11.575480699539175"));   // and zoom to Munich
        }

        // load the locations and display them on the map

        GetLocations();
    }

     

    // calls the WS and retrieves the Locations. Since this call is async we need
    // to wire up a method which should be called when the call to the webservice
    // succeeds and one if the call fails
    function GetLocations() {

        // wire up the methods to call in case of success and failure
        ShowLocationsOnVirtualEarth.Locations.set_defaultSucceededCallback(OnSucceededCallbackRoute);
        ShowLocationsOnVirtualEarth.Locations.set_defaultFailedCallback(OnErrorCallbackRoute);

        // call the webservice
        ShowLocationsOnVirtualEarth.Locations.GetLocations();
    }

     

    // Callback function invoked when the call to
    // the Web service methods succeeds.
    function OnSucceededCallbackRoute(result) {

     

        // draw the locations on the map
        DrawLocationsOnMap(result);
    }

     

    // this function draws the locations on a map
    function DrawLocationsOnMap(ListOfLocations) {

        if ((map != null) && (ListOfLocations != null) && (ListOfLocations.length > 0)) {

     

            // this array holds all the VELatLong values
            // used later to set the zoom of the map to display
            // all the locations 
            var points = new Array();
            var vELatLong;

     

            // draw the Locations on the map
            for (i = 0; i < ListOfLocations.length; i++) {          

                vELatLong = CreateVELatLongFromLocations(ListOfLocations[i]);
                points[i] = vELatLong;           

                // add the location to the map
                map.AddShape(AddDot(vELatLong, 
                                    ListOfLocations[i].Name, 
                                    ListOfLocations[i].Description, 
                                    ListOfLocations[i].MatchedAddress,
                                    ListOfLocations[i].URL));

     

                // Zoom the map according to all locations
                map.SetMapView(points);
            }
        }
    }

     

    // ************************************************************
    // *** some tools ;-)                                       ***
    // ************************************************************

    // Converts a Location into a VELatLong object
    // Parameters:
    // Location: a Location
    // return: a VELatLong instance
    function CreateVELatLongFromLocations(Location) {
        return new VELatLong(Location.Latitude, Location.Longitude);
    }

     

     

    // Creates a custom VEShape (which represents a dot on the map)
    function AddDot(Point, Name, Description, MatchedAddress, URL) {

     

        var shape = new VEShape(VEShapeType.Pushpin, Point);
        shape.SetTitle(Name);   

        var descriptionText = '<b>Description:</b> ' + Description + 
                              '<br /><br /><b>Address:</b> ' + MatchedAddress + 
                              '<br /><br /><b>Homepage:</b> <a href = "' + URL + '">' + URL + '</a>';   

        shape.SetDescription(descriptionText);
        shape.SetCustomIcon('<div><img src="images/info.png" /></div>');
        return shape;
    }

     

     

    // Callback function invoked when the call to
    // the Web service methods fails.
    function OnErrorCallbackRoute(error) {
        alert("Error (route): " + error.get_message());
    }

     

    if(typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

    And that's it resulting in

    To make life even easier you can download the entire solution here and the database here.

    Cheers. Be sure to let me know what you think!

       Daniel

    P.S.: As always this code is "as is" and NOT intended to be used in product use! Note also that this approach might not be the best solution if you only want to display one map with no interaction. If this is your goal make sure to embed the location data in your site to prevent the additional postback to the server (probably using RegisterClientScriptBlock or similar).

    P.P.S. You can geocode your data programmatically using the CustomerDataService class as well. A good place to start is http://msdn2.microsoft.com/en-us/library/aa491870.aspx.

  • <dw:daniel_walzenbach runat="server" />

    Some HTML Editors for ASP.NET...

    • 7 Comments

    The following are some HTML Editors for ASP.NET providing "Rich Text box" functionality and are definitely worth a try.

    FreeTextBox >> http://freetextbox.com/
    FreeTextBox

    FCKEditor >> http://www.fckeditor.net/
    FCKeditor

    TinyMCE >> http://tinymce.moxiecode.com/
    TinyMCE

    This list is by no means complete. There are a couple of other Rich Text editors on the ASP.net control gallery like the Telerik RadEditor. Be sure not to miss them! If you favor other editors just drop a line in the comments. Thanks!

    Cheers!

       Daniel

  • <dw:daniel_walzenbach runat="server" />

    Wie referenziere ich in JavaScript ein Control dessen Namen durch INamingContainer geändert wurde?

    • 7 Comments

    Was ist das Problem?

    Vielleicht haben Sie schon bemerkt, dass clientseitige IDs von Controls gelegentlich von den ursprünglich vergebenen IDs abweichen. Dieses Phänomen tritt immer dann auf, wenn Controls in Container eingefügt werden, die das Interface INamingContainer implementieren. Anbei ein kleines Beispiel:

    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
       
    <asp:TextBox ID="TextBox1" runat="server" />
       
    <br />
       
    <asp:Button ID="Button1" runat="server" Text="Button" />
    </
    asp:Content>

    In diesem Beispiel wurden zwei Controls in einen ContentPlaceHolder eingefügt woraus ASP.NET den folgenden Markup Code erzeugt:

    <div>
       
    <input name="ctl00$ContentPlaceHolder1$TextBox1" type="text" id="ctl00_ContentPlaceHolder1_TextBox1" />
       
    <br />
       
    <input type="submit" name="ctl00$ContentPlaceHolder1$Button1" value="Button" id="ctl00_ContentPlaceHolder1_Button1" />
    </div>

    Problematisch wird es nun, wenn Sie versuchen in JavaScript über die ID des Controls auf das Control zuzugreifen. Da die ID des Controls von ASP.NET geändert wurde findet getElementById in dem folgenden Beispiel kein Control und der Code resultiert in einem Scriptfehler (Fehler 21, Objekt erforderlich).

    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

        <script type="text/javascript">
            function SayHello() {
               
    alert("Hallo " + document.getElementById("TextBox1").value);
            } 
        </script>

        <asp:TextBox ID="TextBox1" runat="server" />
       
    <br />
       
    <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="SayHello();" />

    </asp:Content>

    Warum verhält sich ASP.NET so?

    In dem Beispiel ändert ASP.NET den Namen der Controls um eindeutige IDs auf dem Client zu garantieren. Befände sich beispielsweise auf der Seite ein weiterer ContentPlaceHolder mit einer TextBox mit gleicher ID käme es zu einem Namenskonflikt. Verantwortlich für diese Änderung ist das Interface INamingContainer. Wenn ein Control INamingContainer implementiert (in diesem Fall ContentPlaceHolder1) erzeugt ASP.NET UniqueIDs für jedes ChildControl (in diesem Fall TextBox1 und Button1) indem die UniqueID des NamingContainers und die UniqueID des ChildControls mit einem Doppelpunkt verknüpft werden. Um clientseitig auf ein Control zugreifen zu können gibt es die ClientID die ebenso wie die UniqueID eindeutig für eine Webseite ist. Die ClientID ist die "scriptfreundliche" Version der UniqueID und verwendet im Gegensatz zu der UniqueID einen Unterstrich als Trennzeichen.

    Was ist die Lösung?

    Neben der Möglichkeit die voraussichtliche ClientID im Vorfeld in den JavaScript Code einzufügen (nein, das wollen Sie NICHT!!!) können Sie die ClientID über DataBinding Inline Code in Ihren Code überführen:

    <script type="text/javascript">

        function SayHello() {
           
    var con = document.getElementById("<%= TextBox1.ClientID %>");
           
    alert("Hallo " + con.value);
       
    }

    </script>

    Alternativ haben Sie übrigens auch die Möglichkeit die ClientID über ClientScript.RegisterClientScriptBlock auf der Seite verfügbar zu machen:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim js As String = "function GetTextBox1() { return document.getElementById('" & TextBox1.ClientID & "'); }" 
        ClientScript.RegisterClientScriptBlock(Me.GetType, "TextBox1_ClientID", js, True)

    End Sub

    Happy Coding!

    Daniel

    20071018 - DataBinding Inline Code; Danke Hannes!

  • <dw:daniel_walzenbach runat="server" />

    How do I edit tabular data/data in a DataGridView in a details form?

    • 7 Comments

    Abstract
    This sample shows how to edit data from a DataGridView in a details form which opens when one double clicks on the RowHeader of the DataGridView. Since both forms are bound to the same datasource one sees an instant update on both forms when the user decides to save the data and additional roundtrips to the database are avoided. It also provides a brief introduction to DataBinding in .NET.
    EditDetailsForm.png

    Source Code
    Visual Basic | C#

    Additional Resources
    Connecting to Data in Visual Studio
    Getting Started with Data Access
    Windows Forms Data Binding
    Forms over Data Video Series

    Prerequisites
    The examples were created using Visual Basic 2008 Express (free download)/Visual C# 2008 Express (free download) but do also apply to earlier versions of Visual Studio (with minor modifications).

    Enjoy!


       Daniel

  • <dw:daniel_walzenbach runat="server" />

    Daily .Net Feeds - ASP.Net 2.0 - Advanced - Day 13

    • 7 Comments

    Hi Everyone,

    Welcome back!!!

    As mentioned earlier, today we will be wrapping up with the discussion about the ASP.Net 2.0 reserved folders. Let's take a look and understand the other ASP.Net special folders that we didn't consider yesterday.

    The App_Data Folder:

    The App_Data folder is expected to contain data stores local to the application. It typically contains data stores in the form of files such as Microsoft Access or Microsoft SQL Server Express databases, XML files, text files, and whatever else your application can support. The contents of the folder are not processed by ASP.NET. The folder is the default location where ASP.NET providers store their data.

    Note: The default ASP.NET account is granted full permissions on the folder. If you happen to change the ASP.NET account, make sure that the new account is granted read/write permissions on the folder.

    The App_GlobalResources Folder:

    Let's quickly understand what are resources? Just like other applications, an ASP.NET application can, and often should, use resources. Resources are an effective way to isolate localizable portions of the application's user interface. In general, a resource is non-executable text associated with the program. Typical resources are images, icons, text, and auxiliary files, but any serializable object can be considered a resource. Application resources are stored outside of the application so that they can be recompiled and replaced without affecting and recompiling the application itself.

    In ASP.NET 1.x, compiling resources inside an assembly (or satellite assemblies), although done by Visual Studio but was still a rather transparent task and more often developers need to be aware of several minute details to manage these resources. Basically, an ASP.NET application needs to have a primary assembly to contain the default or neutral resources for the application. In addition, we deploy a number of satellite assemblies, each containing localized resources for a particular culture we want to support. We have to manually compile XML-based resource files (those with a .resx extension) into a .resources binary file. These files can be either embedded in a .NET executable or compiled into satellite assemblies. We use the Resource File Generator (resgen.exe) utility to convert text and XML-based resource files into .resources files. The resource file names follow the naming convention baseName.cultureName.resources. Usually, the base name is the name of the application. A typical command line could be as follows:

    resgen.exe MyAppName.resx MyAppName.it.resources

    Once created, the .resources file should be embedded into an assembly, or it can even be used as is as a resource container. To embed the resource file into a satellite assembly, we use the Assembly Linker tool (al.exe). On the command line, we indicate the culture (it in our example, which represents Italian) and the name of the assembly.

    al /out:MyAppName.resources.dll /c:it /embed:MyAppName.it.resources

    After we compile our satellite assemblies, they will all have the same name. We deploy them in distinct subdirectories, each named after the culture. Fortunately, with ASP.NET 2.0, gone are the days of satellite assemblies. More precisely, satellite assemblies are still there, but they are a thing of the past for developers thanks to the App_GlobalResources reserved folder. Any .resx files located within the folder are automatically compiled to satellite assemblies. The name of the .resx file contains culture information to help the ASP.NET runtime environment with the assembly generation. The following files—resources.resx, resources.it.resx, resources.fr.resx—generate the neutral assembly and satellite assemblies for the Italian and French cultures respectively. The neutral assembly is the default culture resource used by the application if no specific culture is called for. Resource files located in the App_GlobalResources folder are global to the application and can be referenced from within any page. Resource reading results are greatly simplified as compared to ASP.NET 1.x:

    <asp:Label ID="Label1" Runat="server" Text="<%$ Resources:ResxFile, MyResName %>" />

    We can now bind global resources declaratively using the newest $-expression named Resources. (As already mentioned in one of the session, we'll cover $-expressions in more detail during one of the oncoming sessions) For now, the expression takes two parameters—the name of the .resx source file (no extension), and the name of the resource to retrieve. To access resources programmatically, you resort to the following code:

    HttpContext.GetGlobalResourceObject(resxFile, MyResName);

    Both parameters are strings and have the same role as the parameters in the $-expression. Moreover, the implementation of the $- expression Resources uses GetGlobalResourceObject internally.

    The App_LocalResources Folder:

    App_LocalResources is a subdirectory located below the folder that contains some ASP.NET pages. The folder can be filled with .resx files named after the pages located one level upper in the hierarchy. Assuming that the parent folder contains test.aspx, here are few feasible resource files you can find in the App_LocalResources folder: test.aspx.resx, test.aspx.it.resx, test.aspx.fr.resx. Obviously, resources stored in the aforementioned files have an effect only on test.aspx and are visible (and can be used) only from within the linked page.

    How do you access a page-specific resource? For programmatic access, you use the following code:

    HttpContext.GetLocalResourceObject("/ProAspNet20/ResPage.aspx", "PageResource1.Title");

    The first parameter indicates the virtual path of the page; the second parameter is the resource name. For declarative access, you use the meta:ResourceKey attribute. Here's an example:

    <asp:Button ID="Button1" Runat="server" meta:resourcekey="ButtonResource1" />

    The declaration associates a unique resource key with the specified button instance. The local .resx file will contain entries of the form prefix.name, where prefix is a resource key and name is a property name on the bound control. To give the button a localizable caption (the Text property), you simply create a ButtonResource1.Text entry in the resource file.

    Resource files found in both the local and global resource folders are compiled to create classes for satellite assemblies. The net effect is that developers create .resx files and test the page. The ASP.NET compilation machinery does the rest.

    The App_Themes Folder:

    The App_Themes folder defines themes for ASP.NET controls. Each theme takes a folder under App_Themes. Defined, a theme is a collection of files with style information. Compiled, the contents of the files in a theme folder generate a class that, invoked by the page, programmatically sets styles on themed controls.

    The App_Themes folder lists themes local to the application. An application can also inherit global themes defined in the following folder:

    %WINDOWS%\Microsoft.NET\Framework\[version]\ASP.NETClientFiles\Themes

    From the compilation perspective, there's no difference between global and local themes. If a theme with a given name exists both locally to the application and globally to the server machine, the local theme takes precedence.

    The App_WebReferences Folder:

    In Visual Studio .NET 2003, an ASP.NET application that requires access to a Web service will obtain the corresponding .wsdl file through the Add Web Reference dialog box. The Web Service Description Language (WSDL) document for the Web service is not sufficient to make the Web service usable from the page. An ASP.NET page is ultimately a managed class and needs another managed class to talk to. So the Web service is wrapped by a proxy class. The proxy class is created by Visual Studio using the services of a command-line tool—wsdl.exe. The proxy class contains as many methods as there are Web methods on the Web service, and it incorporates any custom data type defined by the public interface of the Web service.

    There are no significant costs for developers in this operation. However, developers are clearly dependent on Visual Studio to generate the proxy class. Wouldn't it be easier and simpler if you could just drop the .wsdl file somewhere in the application's tree and have ASP.NET deal with the rest? This is just what the App_WebReferences folder is for.

    It recognizes .wsdl files describing bound Web services, and it generates runtime proxy classes so that ASP.NET pages can place calls to the Web service in a type-safe manner. The App_WebReferences folder can contain subfolders. The name of the subfolder drives the namespace of the resulting proxy class, whereas the WSDL file defines the classname. For example, the samples.wsdl file in MyApp subfolder will originate a proxy class named MyApp.Samples. The dynamically created assembly is named App_WebReferences.xxx.dll, where xxx is a random sequence of characters.

    That's it for today. Thanks for joining!!! See you tomorrow. Tomorrow we will start discussing about Asp.Net 2.0 build providers.

    Thanks,

    Sukesh Khare
    Coordinator Daily .Net Feed Program

  • <dw:daniel_walzenbach runat="server" />

    Endlich ein Flug mit Warteschleife :-)

    • 6 Comments

    Ok, dass ich soetwas mal schreiben würde hätte ich nicht gedacht! Seit ich meinen neuen GPS Empfänger (DG-100 GPS Data Logger) habe, der auch im Flugzeug funktioniert, wollte ich schon immer wissen, wie ein Landeanflug mit Warteschleife aussieht :-) Heute war es dann soweit und hier ist das Ergebnis (leider hat der Empfänger bei der einen Linkskurve den Empfang verloren wodurch sich die Delle erklärt):

    www.woistdaniel.de

    Nachdem inzwischen die http://www.ice-lingen.de, die BASTA! und heute die xtopia 2007 zu Ende gegangen sind habe ich hoffentlich etwas mehr Zeit mich wieder um www.woistdaniel.de zu kümmern. Immerhin stehen ja noch ein paar Punkte aus wie beispielsweise "deep links" oder woistdaniel für alle Anwender zu öffnen. Wer also gerne zukünftig woistdaniel verwenden würde um seine eigenen Routen (Wandern, Hiking, Fahradtouren, Urlaub, etc.) zu verfolgen kann mir gerne schreiben...

  • <dw:daniel_walzenbach runat="server" />

    RAW Codecs for Windows

    • 6 Comments

    We’ve released a page on the Pro Photo site that we will keep updated with all of the RAW format codecs that are released by the camera/software manufacturers.  You can view the page at http://www.microsoft.com/prophoto/downloads/codecs.aspx.

    Cheers

       Daniel

  • <dw:daniel_walzenbach runat="server" />

    Kostenloser Download: Microsoft Visual Basic 2005 - Das Entwicklerbuch

    • 5 Comments

    Auf dem Microsoft Developer Network steht derzeit das "Microsoft Visual Basic 2005 - Das Entwicklerbuch" zum kostenlosen Download bereit :-) Dieses umfassende Arbeitsbuch zur Programmierung mit Visual Basic 2005 von Klaus Löffelmann erläutert nicht nur umfassend die objektorientierte Programmierung mit Visual Basic, sondern blickt auch hinter die Kulissen des Codes, um grundlegendes Verständnis für wichtige Details und Funktionsweisen sicher zu stellen. Behandelt werden die folgenden Themen:

    1. Einführung
    2. Ein Flug über die Weiten der Visual Studio-IDE
    3. Formular-Designer und Codeeditor enthüllt
    4. Tipps & Tricks für das angenehme Entwickeln zuhause und unterwegs
    5. Der Umstieg von Visual Basic 6.0
    6. Der Umstieg von Visual Basic.NET 2002 und 2003
    7. Vorüberlegungen zur objektorientierten Programmierung
    8. Auf zum Klassentreffen!
    9. Klassenvererbung und Polymorphie
    10. Über Structure und den Unterschied zwischen Referenz- und Wertetypen
    11. Typumwandlungen (Type Casting) und Boxing von Datentypen
    12. Beerdigen von Objekten – Dispose, Finalize und der Garbage Collector
    13. Operatoren für benutzerdefinierte Typen
    14. Generische Klassen und Strukturen (Generics)
    15. Ereignisse und Delegaten
    16. Primitive Datentypen
    17. Kulturabhängiges Formatieren von Zahlen- und Datumswerten
    18. Enums (Aufzählungen)
    19. Arrays und Auflistungen (Collections)
    20. Arbeiten mit generischen Typen und generischen Auflistungen
    21. Reguläre Ausdrücke (Regular Expressions)
    22. Serialisierung von Objekten
    23. Attribute und Reflection
    24. Eine philosophische Betrachtung der Vereinfachungen in Visual Basic 2005
    25. Der My-Namespace
    26. Das Anwendungsframework
    27. Programmieren mit Windows Forms
    28. Im Motorraum von Formularen und Steuerelementen
    29. GDI+ zum Zeichnen von Formular- und Steuerelementinhalten verwenden
    30. Entwickeln von Steuerelementen
    31. Mehreres zur gleichen Zeit erledigen – Threading in .NET
    32. SQL Server 2005 und ADO.NET
  • <dw:daniel_walzenbach runat="server" />

    Various Cheat Sheets (.NET, SQL Server, ASP.NET Ajax, CSS, JavaScript, RegEx, ...) - Free Download

    • 5 Comments

    Following is a list of cheat sheets I found over time... Feel free to post additional links if you have other cheat sheets.

    .NET Framework

    C#

    Web Development

    SQL Server

    Office 2007

    Active Directory

    Smart Client

    BizTalk Server

    Microsoft patterns & practices

    Keyboard shortcuts can be found here:

    Cheers!

       Daniel

  • <dw:daniel_walzenbach runat="server" />

    Do you know your language? Solving the tiny C# quiz :-)

    • 5 Comments

    Impressive! Based on this feedback I should do more quizzes ;-) What do you think?

    ((floatobject)1.2F) is not *really* a float, but a float box. You're allowed to cast from float to double, but not from a boxed float to double. You can unbox to float and then convert that to a double via
    double d = (double)((float)1.2F);

    Details can be found at C# Programmer's Reference > Unboxing Conversion.

    Cheers

       Daniel

    20071008, 23:58: Typo corrected. Thx Roger!

  • <dw:daniel_walzenbach runat="server" />

    SP1 für Vista rockt!!!

    • 5 Comments

    Es ist unglaublich! Nicht zu fassen sozusagen! Ich habe soeben SP1 für Windows Vista auf meinem Rechner installiert und die Kiste rennt :-) Kein rotierender Donut mehr beim Kopieren von Dateien. Selbst das Löschen derselben geht inzwischen in Sekundenbruchteilen :-) Ich bin restlos begeistert! Der Tag ist gerettet! So kann man auch mit kleinen Sachen Kindern eine Freunde mache ;-)

    In diesem Sinne… Alles wird gut ;-)

    Daniel

    Windows Vista Service Pack 1 Beta - Build ...
  • <dw:daniel_walzenbach runat="server" />

    Objektorientierte Programmierung mit VB.NET

    • 4 Comments

    Da die Objektorientierte Entwicklung für viele Entwickler immer noch ein Buch mit sieben Siegeln ist spreche ich am Dienstag, den 4. Dezember 2007, 18:00 – 22:00 Uhr bei der .NET Usergroup Frankfurt über Objektorientierte Programmierung mit VB.NET.

    Abstract:
    Seit der ersten Version des .NET Framework ist VB.NET eine durch und durch objektorientierte Sprache. Anders als in VB 6.0 ist der Umgang mit Objekten hier keine Kür, sondern Pflicht und mit dem Wandel einher gehen objektorientierte Konzepte wie Klassen und Objekte, Kapselung, Vererbung, Polymorphismus, Schnittstellen, usw. Welche Konsequenzen dieser Wandel für Entwickler hat, was die Vorteile der Objektorientierten Programmierung (OOP) sind und wie sich diese in konkreten Codebeispielen äußern zeigt Daniel Walzenbach, Developer Evangelist der Microsoft Deutschland GmbH. Im Anschluss einer Einführung in die OOP beleuchtet Daniel außerdem komplexere Themen wie Ereignisse, Boxing, Polymorphie, Delegates, usw.
    Dieser Vortrag bietet zum einen Visual Basic-Programmieren mit fundamentalen bzw. fortgeschrittenen Kenntnissen einen guten Einstieg bzw. eine Vertiefung der OOP, sondern zum anderen auch praktizierenden VB.NET Programmierern die Möglichkeit ihr Wissen zu vervollständigen und vielleicht existierende Wissenslücken zu schließen.

    Bis bald in FFM!

       Daniel

    P.S.: Wie immer bin ich an jeder Art von Feedback interessiert! Konkret würde mich in diesem Fall allerdings interessieren in wiefern o.g. Thema von Belang ist? Allgemeiner ließe sich die Frage auch so formulieren ob grundsätzlich Interesse an "älteren" Technologien besteht oder ob es immer das "Neuste vom Neuen" sein muss?

  • <dw:daniel_walzenbach runat="server" />

    Do you know your language? This time it's the tiny VB quiz ;-)

    • 4 Comments

    Dim x = -2147483648
    Dim y = Integer.MinValue

    Well, the question is as easy as that - what Types are x and y and what's the reason?

    Cheers

       Daniel

    P.S. Needless to say that you shouldn’t use the VB.NET compiler but the one in your head ;-)

  • <dw:daniel_walzenbach runat="server" />

    Wie sehe ich welche SQL Befehle eine Linq to SQL Abfrage erzeugt?

    • 4 Comments

    Mit Linq ist es sehr einfach komplexe Abfragen auf eine Liste von Objekten anzuwenden. Um einmal hinter die Kulissen zu schauen eignet sich die Property Log des DataContext die, wie in diesem Beispiel zu sehen, die SQL Query auf der Console ausgibt.

    Dim db As New NWDataClassesDataContext

    Dim result = From c In db.Customers _

                 Where c.City.StartsWith("M") _

                 Group c.City By key = c.City Into Group _

                 Select key, Group.Count

     

    db.Log = Console.Out

     

    For Each row In result

        Console.WriteLine(row)

    Next

    db.Log = Console.Out erzeugt daraufhin die folgende Ausgabe:
    Durch Linq to SQL erzeugte Query

    Für C# gibt es außerdem einen "LINQ to SQL Debug Visualizer" der die erzeugte Query im Debugger anzeigen kann.

    Happy Coding!

    Daniel

  • <dw:daniel_walzenbach runat="server" />

    Yeah! Popfly Goes Public!

    • 4 Comments
    Microsoft Popfly

    Finally, Popfly goes public :-) You don't longer need to get an invitation or wait to get your account approved. Get your account today on www.popfly.ms and get funky ;-)

  • <dw:daniel_walzenbach runat="server" />

    SQL Server - Error 15023: User already exists in current database

    • 4 Comments

    Alright, cause this troubles me regularly when restoring databases... ;-) If you ever encounter Error 15023: User already exists in current database you need to use sp_change_users_login to map an existing database user to a SQL Server login.

    sp_change_users_login [ @Action = ] 'action'
         [ , [ @UserNamePattern = ] 'user' ] 
         [ , [ @LoginName = ] 'login' ] 
             [ , [ @Password = ] 'password' ]

    HTHs

    Daniel

  • <dw:daniel_walzenbach runat="server" />

    How to connect Visual Studio 2008 to SQL Server 2008 CTP?

    • 4 Comments

    Annoyed that you can't use Visual Studio 2008 Server Explorer to connect to a SQL Server 2008 CTP installation? This CTP enables developers to use Visual Studio 2008 with SQL Server 2008 February CTP.

    As always... Have fun ;-)

       Daniel

  • <dw:daniel_walzenbach runat="server" />

    Cool Photoshop Tutorials available online for free

    • 4 Comments

    Well, I'll probably get fired for this (Just kidding! Have a look @ Life At Microsoft - The Truth Revealed to see how working for MS REALLY looks like...) but I wanted to make you aware of some cool Photoshop tutorials. We might face the fact that paint isn't the first choice of serious photographers ;-)

       Daniel

  • <dw:daniel_walzenbach runat="server" />

    How to develop Microsoft Virtual Earth applications in managed code like C# instead of JavaScript

    • 4 Comments

    Microsoft Live Labs VoltaVolta, a Live Labs technology preview launched last week, includes bindings for Virtual Earth. The VoltaVirtualEarth library allows developers using Volta to build Virtual Earth applications for the browser, in managed code. This translates into static type checking, IntelliSense, integrated debugging, and many others—see the Volta docs for a list of the benefits.

    If you're interested in seeing it in action a subset of the Virtual Earth interactive SDK is available online, with the code written in C# rather than JavaScript. For example, here's the code for the Show/Hide a shape sample:

    private void ShowHideShape()
    {
        var map = new Microsoft.LiveLabs.Volta.VirtualEarth.Map(mapDiv);
        map.LoadMap();
        Shape shape = new Shape(ShapeType.Pushpin, map.GetCenter());
        shape.SetTitle("My pushpin");
        shape.SetDescription("This is a pushpin.");
        map.AddShape(shape);
        doShowShape.Click += delegate { shape.Show(); };
        doHideShape.Click += delegate { shape.Hide(); };
    }

    With the caveat that Volta is a technology preview, if it looks like something you'd like to take a closer look at please do give it a try and provide your feedback to the community forum.

    To cool!

       Daniel

Page 1 of 12 (284 items) 12345»