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

    How to enable remote connections in SQL Server 2008?

    • 84 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" />

    Frohe Weihnachten…

    • 0 Comments

    … sowie einen guten und erfolgreichen Start in das neue Jahr wünsche ich allen Lesern meines Blogs!

    Frohe Weihnachten!

    Festliche Grüße

    Daniel Walzenbach

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

    How to use String.Format in PowerShell?

    • 1 Comments

    Hah! (We’re back ;-) ) It’s as easy as that:

    PS > [string] :: Format( "Hello {0} {1} :-)", "Daniel", "Walzenbach")
    Hello Daniel Walzenbach :-)

    Needless to say that other formatting – like Currency formatting – works as well

    PS > [string] :: Format( "{0:C}", 1234567890)
    $1,234,567,890.00

    Check out Formatting Types on the .NET Framework Developer's Guide or SteveX Compiled - String Formatting in C# (nice cheat sheet) for more examples.

    Cheers!

       Daniel

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

    How to insert binary data (like images/documents) into a SQL Server database with SQL Server Management Studio?

    • 3 Comments

    If you quickly want to insert some binary data (like images, word documents, pdfs) into a database writing a front-end application for this talk might be a bit of an overkill… Fortunately, this is a pretty straight-forward talk in SQL Server Management Studio :-)

    The following example updates the Categories table of the good ol’ Northwind database to store the images, updates two categories with images and adds another category and an image.

     /* Add anadditional column to the Categories table to store the image */

    ALTER TABLE dbo.Categories ADD
          CategoryPicture VARBINARY(MAX) NULL
    GO

    /* update thetable to insert some images */

    UPDATE Categories
    SET CategoryPicture =
          (SELECT * FROMOPENROWSET(BULK N'C:\Temp\Beverages.jpg', SINGLE_BLOB) AS CategoryImage)
    WHERE CategoryID = 1

    UPDATE Categories
    SET CategoryPicture =
          (SELECT * FROMOPENROWSET(BULK N'C:\Temp\Condiments.jpg', SINGLE_BLOB) AS CategoryImage)
    WHERE CategoryID = 2

    GO

    /* Insert a new category with an image */

    INSERT INTO Categories(CategoryName, CategoryPicture)
    Values ('Another Category', (SELECT * FROM OPENROWSET(BULK N'C:\Temp\AnotherCategory.jpg', SINGLE_BLOB) AS CategoryImage))

    Enjoy!

       Daniel

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

    Das Chamäleon ASP.NET

    • 1 Comments

    Ein beständiger Quell der Freude bei der Entwicklung von Webseiten ist, dass verschiedene Browser und verschiedene Versionen des gleichen Browsers jeweils unterschiedliche Features unterstützen. Als Resultat stellen verschiedene Browser die gleiche HTML-Seite unterschiedlich dar und Entwickler waren jahrelang gezwungen Ihre Seiten für verschiedene Browser zu optimieren, wollten Sie dem Besucher ihrer Seite eine optimale "User Experience" anbieten.

    Für ASP.NET Entwickler gehört dieses Problem sei der ersten Version von .NET (bis auf ein paar Ausnahmen) der Vergangenheit an. ASP.NET Webseiten setzen sich zu einem großen Teil aus ASP.NET Controls zusammen. Diese Controls sind anhand der Benutzeragenteninformationen in der Lage den Browser, der die Seite anfordert, zu erkennen und können daraufhin die Ausgabe auf die Darstellung des Browsers entsprechend anpassen. Die Benutzeragenteninformationen stehen übrigens als UserAgent-Eigenschaft oder als HttpRequest-Objekt zur Verfügung.

    Entsprechend der Fähigkeit von Browsern, bestimmte Inhalte darstellen zu können, werden Browser in zwei Klassen unterteilt: "uplevel"-Browser (neuere Versionen) und "downlevel"-Browser (frühere Versionen).

    Browser und Clientgeräte, die als "uplevel" bezeichnet werden, bieten in der Regel Unterstützung für:

    • ECMAScript (JScript, JavaScript), Version 1.2.
    • HTML, Version 4.0
    • Microsoft Document Object Model (MSDOM, Microsoft-Dokumentobjektmodell).
    • Cascading Stylesheets (CSS).

    Browser und Clientgeräte, die als "Downlevel" bezeichnet werden, unterstützen nur HTML, Version 3.2

    Um die Darstellung der Seite explizit zu steuern, anstatt sich auf die automatische Browsererkennung zu verlassen, kann die ClientTarget-Eigenschaft der Seite über die vordefinierten Standardeinstellungen ie5, ie4, uplevel und downlevel festgelegt werden. Mit der Angabe des downlevel-Alias kann die Darstellung einer Seite – unabhängig von dem eingesetzten Browser – mit HTML 3.2-kompatiblen Elementen erzwungen werden. Analog erzwingt die Angabe von uplevel die Ausgabe von CSS-Formatattributen, unabhängig davon, ob der Browser, der die Seite anfordert, diese verwenden kann oder nicht.

    Ein kleines Beispiel soll dieses Konzept illustrieren. Zu diesem Zweck wurde in diesem Codebeispiel die ClientTarget-Eigenschaft in der Seitendirektive der Webseite explizit auf uplevel gesetzt ist.

    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" ClientTarget="uplevel" %>

     

    <!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>Benutzerverwaltung</title>

    </head>

        <body>

            <form id="form1" runat="server">

                <div>

                    <asp:Label

                        ID="Label1" runat="server" Text="Benutzerverwaltung"

                        Font-Bold="False" Font-Italic="True"

                        Font-Names="Verdana" ForeColor="DarkGray"

                        Font-Size="Larger" />

                    <br />

                    <br />

                    <asp:Label

                        ID="Label2" runat="server" Text="Name:"

                        Font-Names="Verdana" ForeColor="DarkGray"

                        Font-Bold="False" Font-Size="Small" />

                    <br />

                    <asp:TextBox ID="txtName" runat="server" />

                    <asp:RequiredFieldValidator

                        ID="RequiredFieldValidator1" runat="server"

                        ControlToValidate="txtName"

                        ErrorMessage="Bitte geben Sie einen Namen ein." />

                    <br />

                    <br />

                    <asp:Button ID="btnLaden" runat="server" Text="Laden" />

                </div>

            </form>

        </body>

    </html>

    Entsprechend dieser Einstellungen rendern die ASP.NET Server Controls (<asp:Label />, <asp:TextBox />, <asp:RequiredFieldValidator />, <asp:Button ID="btnLaden" />) in dem Beispiel den Inhalt der Seite unterschiedlich.

    ClientTarget="uplevel"

    <!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><title>

          Benutzerverwaltung

    </title></head>

        <body>

            <form name="form1" method="post" action="Default.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="form1">

    <div>

    <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />

    <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />

    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJMTQ5OTQxNDc3ZGSc409E/rebtnJIGPY4lpj9UKIcHg==" />

    </div>

     

    <script type="text/javascript">

    <!--

    var theForm = document.forms['form1'];

    if (!theForm) {

        theForm = document.form1;

    }

    function __doPostBack(eventTarget, eventArgument) {

        if (!theForm.onsubmit || (theForm.onsubmit() != false)) {

            theForm.__EVENTTARGET.value = eventTarget;

            theForm.__EVENTARGUMENT.value = eventArgument;

            theForm.submit();

        }

    }

    // -->

    </script>

     

     

    <script src="/ClientTarget/WebResource.axd?d=OF_ycAeEyoS1YxGgAoI3Fg2&amp;t=632969108944906146" type="text/javascript"></script>

     

     

    <script src="/ClientTarget/WebResource.axd?d=wFFdy1h0cE0vw88ojJditOq7o464AD3s8S-LqSeUmxk1&amp;t=632969108944906146" type="text/javascript"></script>

    <script type="text/javascript">

    <!--

    function WebForm_OnSubmit() {

    if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;

    return true;

    }

    // -->

    </script>

     

    <div>

        <span id="Label1" style="color:DarkGray;font-family:Verdana;font-size:Larger;font-weight:normal;font-style:italic;">Benutzerverwaltung</span>

        <br />

        <br />

        <span id="Label2" style="color:DarkGray;font-family:Verdana;font-size:Small;font-weight:normal;">Name:</span>

        <br />

        <input name="txtName" type="text" id="txtName" />

        <span id="RequiredFieldValidator1" style="color:Red;visibility:hidden;">Bitte geben Sie einen Namen ein.</span>

        <br />

        <br />

        <input type="submit" name="btnLaden" value="Laden" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;btnLaden&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="btnLaden" />

    </div>

     

    <script type="text/javascript">

    <!--

    var Page_Validators =  new Array(document.getElementById("RequiredFieldValidator1"));

    // -->

    </script>

     

    <script type="text/javascript">

    <!--

    var RequiredFieldValidator1 = document.all ? document.all["RequiredFieldValidator1"] : document.getElementById("RequiredFieldValidator1");

    RequiredFieldValidator1.controltovalidate = "txtName";

    RequiredFieldValidator1.errormessage = "Bitte geben Sie einen Namen ein.";

    RequiredFieldValidator1.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";

    RequiredFieldValidator1.initialvalue = "";

    // -->

    </script>

     

    <div>

     

          <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwLr3vKqCwLEhISFCwKct5SxA0qg7S78OUEVS+kzdJhDLF6zY2mx" />

    </div>

     

    <script type="text/javascript">

    <!--

    var Page_ValidationActive = false;

    if (typeof(ValidatorOnLoad) == "function") {

        ValidatorOnLoad();

    }

     

    function ValidatorOnSubmit() {

        if (Page_ValidationActive) {

            return ValidatorCommonOnSubmit();

        }

        else {

            return true;

        }

    }

    // -->

    </script>

            </form>

        </body>

    </html>

    ClientTarget="downlevel"

    <!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><title>

          Benutzerverwaltung

    </title></head>

        <body>

            <form name="form1" method="post" action="/ClientTarget/Default.aspx" id="form1">

    <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />

    <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />

    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJMTQ5OTQxNDc3ZGSc409E/rebtnJIGPY4lpj9UKIcHg==" />

     

    <script type="text/javascript">

    <!--

    var theForm = document.forms['form1'];

    if (!theForm) {

        theForm = document.form1;

    }

    function __doPostBack(eventTarget, eventArgument) {

        if (!theForm.onsubmit || (theForm.onsubmit() != false)) {

            theForm.__EVENTTARGET.value = eventTarget;

            theForm.__EVENTARGUMENT.value = eventArgument;

            theForm.submit();

        }

    }

    // -->

    </script>

     

     

    <script src="/ClientTarget/WebResource.axd?d=OF_ycAeEyoS1YxGgAoI3Fg2&amp;t=632969108944906146" type="text/javascript"></script>

     

    <div>

        <span id="Label1"><i><font face="Verdana" color="DarkGray">Benutzerverwaltung</font></i></span>

        <br />

        <br />

        <span id="Label2"><font face="Verdana" color="DarkGray" size="3">Name:</font></span>

        <br />

        <input name="txtName" type="text" id="txtName" />

        &nbsp;

        <br />

        <br />

        <input type="submit" name="btnLaden" value="Laden" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;btnLaden&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="btnLaden" />

    </div>

     

    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwLr3vKqCwLEhISFCwKct5SxA0qg7S78OUEVS+kzdJhDLF6zY2mx" /></form>

        </body>

    </html>

    Schöne Grüße

    Daniel

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

    Visual Studio 2005 Keyboard Shortcut Reference Poster

    • 4 Comments

    Für die populärsten .NET Sprachen Visual Basic 2005, Visual C# 2005 und Visual C++ 2005 gibt es von dem Visual Studio Team Poster mit den meistverwendeten Shortcuts :-)

    Visual Studio Keyboard Shortcut Reference VB.NET 2005
    Visual Studio Keyboard Shortcut Reference VB.NET 2005

    Visual Studio Keyboard Shortcut Reference C# 2005
    Visual Studio Keyboard Shortcut Reference C# 2005

    Visual Studio Keyboard Shortcut Reference C++ 2005
    Visual Studio Keyboard Shortcut Reference C++ 2005

    Äußerst cool!

  • <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" />

    .NET Framework 3.5 commonly used types and namespaces poster free for download

    • 1 Comments

    Paul Andrew announced the availability of the .NET Framework 3.5 update to the Commonly Used Types and Namespaces poster. Get it while it's still hot and be sure to have a printout stuck behind you on your wall. The link also contains a XPS format file which prints over 16 letter or A4 pages for easy printing ;-)

    Microsoft .NET Framework 3.5

    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" />

    Spaß mit Google Earth/Google Maps

    • 3 Comments

    Google setzt bei der Erstellung von 3D Modellen, bzw. dem Mapping von Fotos auf besagte Modelle auf die Community. Mit Hilfe von SketchUp können 3D Modelle erzeugt werden, auf Google Earth hochgeladen und anschließend freigegeben werden. Interessanterweise führt das immer wieder zu lustigen Ergebnissen ;-)

    Google Maps

    Sieht fast so aus als befände sich ein schwarzes Loch mitten im Zentrum von Seattle :-)

    Wer sich die Karte im Browser anschauen möchte: http://maps.google.de/?ie=UTF8&ll=47.604601,-122.332522&spn=0.003183,0.005413&t=k&z=18&om=1

    Schöne Grüße

    Daniel

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

    How to get a list of all files of a directory (subdirectories included)?

    • 4 Comments

    I needed to create a list of all Code Snippets we ship in Visual Studio the other day containing their title, description and path on disc and size. As you might know, Code Snippets are stored in multiple directories below "%ProgramFiles%\Microsoft Visual Studio 10.0" so I had to traverse all the subdirectories of the aforementioned path to find all snippets.

    Fortunately – linq to the rescue – this came down to a few lines of code :-)

    Dim query = From file In My.Computer.FileSystem.GetFiles("C:\Program Files\Microsoft Visual Studio 10.0", FileIO.SearchOption.SearchAllSubDirectories) _

                Where file.EndsWith(".snippet") _

                Order By file

    This statement gives you a List of Strings (or, to be a bit more precise, a System.Linq.IOrderedEnumerable(Of String)) which you can walk over to do all kinds of crazy things.

    Here is what I did to solve the problem I described above:

    Imports <xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> 

     

    Public Class Form1

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

            Dim query = From file In My.Computer.FileSystem.GetFiles(txtPath.Text, FileIO.SearchOption.SearchAllSubDirectories) _

                        Where file.EndsWith(".snippet") _

                        Order By file

            Dim snippets As New List(Of Snippet)

            Dim snippetDocument As XElement

            Dim snippet As Snippet

            For Each item In query

                snippetDocument = XElement.Load(item)

                If snippetDocument...<Title>.Value IsNot Nothing Then

                    snippet = New Snippet With {.Title = snippetDocument...<Title>.Value.ToString _

                                                , .Description = snippetDocument...<Description>.Value.ToString _

                                                , .Path = item _

                                                , .Size = New System.IO.FileInfo(item).Length}

                    snippets.Add(snippet)

                End If

            Next

            DataGridViewSnippets.AutoGenerateColumns = True

            DataGridViewSnippets.DataSource = snippets

        End Sub

    End Class

     

    Public Class Snippet

        Private _Title As String

        Private _Description As String

        Private _Path As String

        Private _Size As Long

        Public Property Title() As String

            Get

                Return _Title

            End Get

            Set(ByVal value As String)

                _Title = value

            End Set

        End Property

        Public Property Description() As String

            Get

                Return _Description

            End Get

            Set(ByVal value As String)

                _Description = value

            End Set

        End Property

        Public Property Path() As String

            Get

                Return _Path

            End Get

            Set(ByVal value As String)

                _Path = value

            End Set

        End Property

        Public Property Size() As Long

            Get

                Return _Size

            End Get

            Set(ByVal value As Long)

                _Size = value

            End Set

        End Property

    End Class

    Btw, if you bind the result to a DataGridView you can copy&paste from there into excel. Needo :-)

    Cheers!

       Daniel

    P.S. If you'd like to understand why you need the Imports <xmlns="http... at the beginning of the code check the follow-up article I wrote.

    P.P.S. You can download the source code from the MSDN Code Gallery.

    Edited April 29, 2009: Included the "Imports" statement and did some cleanup work.

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

    Halloween - Coding4Fun Style

    • 2 Comments

    Was für einen besseren Beweis gibt es dafür, dass Programmieren Spaß macht, als die Halloweenartikel auf der amerikanischen „Coding4Fun“-Seite. Im Angebot wären...

    A Motion-Detecting, Blood Squirting Halloween Skull A Motion-Detecting, Blood Squirting Halloween Skull – Just what you need to keep those pesky kids off your lawn.
    Reusable Body Parts Reusable Body Parts – Nothing shows how far you can stretch your developer skills like controlling an animatronic hand using Visual Studio Express.
    Scary Halloween Application Scary Halloween Application – If you thought Vista was scary, just wait until your working late one night and your screen starts dripping blood, flashing scary pictures, and screaming at you.
    HAHAHAHAHAHAHA :-)
  • <dw:daniel_walzenbach runat="server" />

    How to get the Base Directory of an application?

    • 1 Comments

    Well, to be honest that’s actually quite easy, nevertheless I keep forgetting it all the time (pretty much like Error 15023: User already exists in current database). Seems like I enter an age where my short term memory is already gone but the long term memory hasn’t arrived yet ;-)

    So, without further frills, that’s how it works:

    Dim myFile = String.Format("{0}\myFile.xml", _
                              AppDomain.CurrentDomain.BaseDirectory)

    Happy coding!

       Daniel

  • <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" />

    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" />

    JETZT ONLINE! Die ersten Bird´s eyes für Deutschland!

    • 0 Comments

    So langsam wird Virtual Earth seinem Namen gerecht… Auf www.local.live.com gibt es hochauflösende Bilder von diesen Städten (weitere folgen):

    Aalen, Aschaffenburg, Augsburg, Baden-Baden, Bamberg, Bayreuth, Binz, Brandenburg, Chemnitz, Cottbus, Dessau, Dresden, Erfurt, Erlangen, Freiburg im Breisgau, Gera, Goppingen, Goerlitz, Halle, Hanau, Heilbronn, Ingolstadt, Jena, Karslruhe, Kempten (Allgaeu), Konstanz, Landshut, Leipzig, Lubeck, Ludwigsburg, Magdeburg, Mannheim, Munchen, Neumeunster, Nurenburg and Fuerth, Offenburg, Pforzheim, Plauen, Potsdam, Reutlingen, Rosenheim, Rostock, Saarbruecken, Sassnitz, Schwaebisch Gmuend, Sindlefingen, Speyer, Stralsund, Stuttgart, Trier, Teubingen, Ulm, Villingen-Schwenningen, Waiblingen, Weimar, Wolfsburg, Wuerzburg

    Als kleines Beispiel zwei Bilder:

    Der Mannheimer Wasserturm

    München Viktualienmarkt und der "Alte Peter"

    Viel Spaß beim Surfen ;-)

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

    .NET 3.5 Enhancements Training Kit ready to download

    • 2 Comments

    The .NET 3.5 Enhancements Training Kit covers the technologies in the .NET 3.5 SP1 release and the out of band releases that are a part of the same wave, namely ASP.NET MVC and the ASP.NET Silverlight controls. Currently, the training kit contains six hands-on labs, made up of the following technologies:

    1. ADO.NET Data Services
    2. ADO.NET Entity Framework
    3. ASP.NET AJAX History
    4. ASP.NET Dynamic Data
    5. ASP.NET MVC
    6. ASP.NET Silverlight controls

    Additional information can be found here.

    Cheers

       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" />

    Eindrücke von der TechEd Europe 2006

    • 2 Comments

    Wow! Diese Woche ging schnell rum. Nicht, dass ich mich sonst langweilen würde aber diesmal war es extrem… Montagabends noch der zweite Webcast der Reihe „Get the BASICs, Visual Basic .NET für Einsteiger und Umsteiger“ und im Anschluss direkt in den Flieger nach Barcelona auf die TechEd Europe 2006.
    Anbei einige Bilder exzellenter Sessions die ich besuchen konnte während ich nicht in dem „Ask the Experts“ Bereich gearbeitet habe. Leider konnte Nikhil Kothari dieses Jahr aufgrund einer Lebensmittelvergiftung nicht auf der TechEd sprechen :-(

    Anders Hejlsberg
    Anders Hejlsberg bei seinem Vortrag "Using the .NET Language Integrated Query (LINQ) Framework with Relational Data".
    Bob Beauchemin
    Bob Beauchemin spricht über "Coding SQL Server 2005: Plan Guides and Plan Forcing". Unter vielen excellenten Vorträgen dieses Jahrs meiner Meinung nach mit einer der Besten.
    Brian Randell
    Brian Randell "Introducing Visual Studio (VS) 2005 Team Edition for Database Professionals".
    Fritz Onion
    Fritz Onion zeigt "10 Undiscovered Features of ASP.NET 2.0".
    Jay Schmelzer
    Jay Schmelzer, Group Programm Manager VB.NET, über "VB-Now, VB-Next".
    Kimberly Tripp
    Kimberly Tripp während ihres excellenten Vortrags "SQL Server 2005: Optimizing Procedural Code". Kimberly stand auch dieses Jahr wieder ganz oben auf der Liste der beliebtesten Sprecher.
    Paul S. Randal
    Paul S. Randal, Lead Program Manager im Microsoft SQL Server Storage Engine Team, erklärt die Storage Engine in seiner Session "A day in the Life of a Query - What happens when when you thye GO?".
    Wayne Smith
    Wayne Smith spricht über "Developing and Designing Standard Based Web Applications with Expression Web Designer".
    Mein Kollege Dirk Primbs im Gespräch mit einem Teilnehmer
    Mein Kollege Dirk Primbs im Gespräch mit einem Teilnehmer der TechEd.
    Kostja und Oliver
    Mein ehemaliger Kollege Constantin Klein (Freudenberg) neben meinem derzeitigen Kollegen Oliver Scheer (Microsoft).

    Dienstags waren wir mit einigen Journalisten zu Abend essen und mittwochs hatten wir das Glück abends noch etwas Zeit in der Innenstadt von Barcelona zu verbringen. Zusätzlich auch einige Bilder unserer Unterkunft im Retro Style ;-)

    Bodega la Palma
    Im Bodega la Palma in der Innenstadt von Barcelona gibt es die leckersten Tappas.
    Spanische Delikatessen
    Einer von vielen Marktständen mit den feinsten spanischen Spezialitäten.
    Obststand
    Früchte in jeder nur erdenklichen Auswahl.
    Schokolade
    Schokolade in allen Farben und Formen. Lecker, lecker, lecker :-))
    VINCCI CONDAL MAR
    Das VINCCI CONDAL MAR. Wahrscheinlich das coolste Hotel in Barcelona. Retro pur!
    VINCCI CONDAL MAR
    Der Flur war schon ziemlich stylisch...
    Zimmer im VINCCI CONDAL MAR
    ... und die Zimmer standen in nichts nach ;-)
    Zimmer im VINCCI CONDAL MAR
    ohne Worte...
    Zimmer im VINCCI CONDAL MAR
    Wie stylisch ist das?

    Bis zur nächsten TechEd! Schöne Grüße von Daniel

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

    Spaß mit VB.NET :-) Achtung! Nerds only!

    • 1 Comments

    Ok. Eigentlich wollte ich ja schon im Bett sein aber das ist dann doch zu arg ;-)

    Fun with VB.NET

    Noch cooler ist jedoch, dass obiger Code tatsächlich lauffähig ist und folgende Ausgabe erzeugt :-)))

    Fun with VB.NET

    Kudos an Kit George! In diesem Sinne…

    Daniel

    Nachtrag (20070913_1135)
    P.S.: Den Quellcode gibt's übrigens auf http://blogs.msdn.com/vbteam/archive/2007/09/06/fun-with-vb.aspx

     

  • <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" />

    Übungsaufgaben und Lösungen zu „Get the BASICs, Visual Basic für Einsteiger und Umsteiger“, Teil 1-3

    • 1 Comments

    "Get the BASICs, Visual Basic für Einsteiger und Umsteiger", Teil 1

    Aufgabe

    Schreiben Sie ein Programm, das mit den Zeichen + I und ein kleines Fenster ausgibt.

    Verwenden Sie die Befehle Console.WriteLine() und/oder Console.Write()

    +--------------------+

    I                    I

    I  VB.NET ist cool!  I

    I                    I

    +--------------------+

    Lösung

    Option Strict On

    Option Explicit On

     

    Module Module1

     

        Sub Main()

     

            ' VB.NET ist cool! in einer Box auf der Console ausgeben

            System.Console.WriteLine("+--------------------+")

            System.Console.WriteLine("+                    +")

            System.Console.Write("+  ")

            System.Console.Write("VB.NET ist cool!")

            System.Console.WriteLine("  +")

            System.Console.WriteLine("+                    +")

            System.Console.WriteLine("+--------------------+")

     

        End Sub

     

    End Module

    "Get the BASICs, Visual Basic für Einsteiger und Umsteiger", Teil 2

    Aufgabe

    Schreiben Sie ein Programm welches den Kreisinhalt (A) berechnet.
    A = πr²

    Verwenden Sie die Befehle Console.WriteLine() und/oder Console.Write() und/oder Console.ReadLine() und System.Math.PI.

    Bitte geben Sie den Radius des Kreises in cm ein: 5

    Der Kreisinhalt eines Kreises mit Radius 5cm beträgt ca. 78,5cm².

    Lösung

    Option Strict On

    Option Explicit On

     

    Module Module1

     

        Sub Main()

     

            Dim Radius As Double

            Dim Kreisinhalt As Double

     

            Console.Write("Bitte geben Sie den Radius des Kreises in cm ein: ")

            Radius = Convert.ToDouble(Console.ReadLine)

     

            ' Kreisinhalt berechnen

            Kreisinhalt = Math.PI * Math.Pow(Radius, 2)

     

            Console.WriteLine("Der Kreisinhalt eines Kreises mit " & _

            "Radius {0}cm beträgt ca. {1}cm².", Radius, Kreisinhalt)

     

        End Sub

     

    End Module

    "Get the BASICs, Visual Basic für Einsteiger und Umsteiger", Teil 3

    Aufgabe

    Schreiben Sie ein Programm welches mit Hilfe einer Schleife

    • die Zahlen 1, 4, 7, 10, 13 und 16 ausgibt.
    • die Quadratzahlen von 0 bis 20, jedoch nicht die Quadratzahl von 10, zeilenweise ausgibt
    • einen halben Tannenbaum ausgibt
      *
      **
      ***
      ****
      *****
      ******
      *******
      ********
      *********
      **********
      ***********
      ***
      ***
      ***

    Lösung

    Option Strict On

    Option Explicit On

     

    Module Module1

     

        Sub Main()

     

     

            ' die erste Aufgabe

            ' Schreiben Sie ein Programm welches mit Hilfe einer Schleife

            ' die Zahlen 1, 4, 7, 10, 13 und 16 ausgibt.

            Console.WriteLine("Aufgabe 1")

            Console.WriteLine("------------------------------------------")

     

            ' die Lösung der ersten Aufgabe

            For i As Integer = 1 To 16 Step 3

     

                Console.Write(i & " ")

     

            Next

     

            ' zwei leere Zeilen ausgeben

            Console.WriteLine()

            Console.WriteLine()

     

     

            ' die zweite Aufgabe

            ' Schreiben Sie ein Programm welches mit Hilfe einer Schleife

            ' die Quadratzahlen von 0 bis 20 zeilenweise ausgibt

            ' Wichtig! Die Quadratzahl der Zahl 10 soll NICHT ausgegeben werden!

            Console.WriteLine("Aufgabe 2")

            Console.WriteLine("------------------------------------------")

     

            ' die Lösung der zweiten Aufgabe

            For i As Integer = 0 To 20

     

                If i <> 10 Then

     

                    Console.WriteLine(" Die Quadratzahl von {0} ist {1}.", i, Math.Pow(i, 2))

     

                End If

     

            Next

     

            ' zwei leere Zeilen ausgeben

            Console.WriteLine()

            Console.WriteLine()

     

     

            ' die dritte Aufgabe

            ' Schreiben Sie ein Programm welches mit Hilfe einer Schleife

            ' einen halben Tannenbaum ausgibt

            Console.WriteLine("Aufgabe 3")

            Console.WriteLine("------------------------------------------")

     

     

            For i As Integer = 0 To 13

     

                For j As Integer = 0 To 13

     

                    If i < 11 Then

                        Console.Write("*")

     

                        If j = i Then

                            Console.WriteLine()

                            Exit For

                        End If

     

                    Else

                        Console.WriteLine("***")

                        Exit For

     

                    End If

     

                Next    ' j

     

            Next    ' i

     

        End Sub

     

    End Module

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

    Free download: Visual Studio 2010 Pro Power Tools

    • 0 Comments

    If you are the .NET Developer using Visual Studio 2010 you’ll love the Visual Studio 2010 Pro Power Tools!

    Visual Studio 2010 Productivity Power Tools

    A set of extensions to Visual Studio Professional (and above) which improves developer productivity.

    • Document Well 2010 Plus (More Info)
      One of the key pieces of feedback that we have received over several versions of Visual Studio is that users want to be able to customize the behaviour of their document tabs.  From the ordering of tabs to the position of the close buttons, user can now configure dozens of different options for their tabs.  Go to Tools -> Options -> Environment -> Document Tab Well to configure these options as you prefer:
      • Tab Well UI
        • Scrollable tabs
          Maintain spatial consistency of the documents that are included in the document well.
        • Vertical tabs
          Document tabs are shown vertically, allowing you to fit more tabs than are normally visible when shown horizontally.
        • Pinned tabs
          Allows you to pin tabs to keep them always visible and available.
        • Show close button in tab well
          Similar to Visual Studio 2008, will show a close button in the document well that will close the active tab.
      • Tab Behavior
        • Remove tabs by usage order (LRU)
          When a new tab is inserted and existing tabs don't fit in the document well, instead of removing the tab at the end of the well it will remove the least recently used tab. This ensures that frequently used tabs are readily available.
        • Show pinned tabs in a separate row/column
          Pinning tabs can quickly cause you to run out of space for regular tabs. The option allows you to always show pinned tabs in a separate row (or column, if displayed vertically) from regular tabs.
      • Sorting
        • Sort tabs by project
          Tabs will be sorted by the project they belong to, thus keeping them always together in the document tab well.
        • Sort tabs alphabetically
          Tabs will be sorted alphabetically. When Sort By Project is turned on, tabs will be sorted first by project and then alphabetically.
        • Sort tab well dropdown alphabetically
          The drop down menu at the right end of the document well is sorted alphabetically. This option allows ordering as the tabs are laid out in the document well.
      • Tab UI
        • Color tabs according to their project or according to regular expressions
          This option permits tabs to be colored according to the project they belong to. This is particularly useful when sorting tabs by project, as it allows you to immediately identify different groups of project documents.
          You can also configure regular expressions and assign a color to each one. If the name of a tab matches the configured regular expression, it will be colored with the assigned color.
        • Miscellaneous options that modify tab UI
          • Show document/toolwindow icon in tab
          • Show close button in tab
          • Modify dirty indicator style
            This option allows you to select from a set of different dirty indicators that you might prefer over the asterisk.
          • Modify minimum and maximum tab size
            Allows you to modify minimum and maximum tab size. Try setting minimum and maximum sizes to the same value, and you will have evenly spaced tabs.
    • Searchable Add Reference Dialog
      The new Add Reference dialog makes it faster and easier for you to find the reference that you are looking for and add it to your VB, C# or F# project.  From the Solution Explorer, simply right click on the References node, select the Add Reference command to see the updated Add Reference Dialog. 
    • Highlight Current Line
      As the resolution of monitors increases, it’s becoming more difficult to find the caret in the code editor.  The highlight current line extension makes it easy to find the caret by highlighting the line that the caret is on in the editor.  You can even configure the default colour by changing the setting for “Current Line (Extension)” and “Current Line Inactive (Extension)” in Tools Options Fonts & Colors. 
    • HTML Copy
      This extension provides support for the HTML Clipboard format when copying code from the editor.  This means that you’ll no longer have to go fix up the formatting of your code when you paste it into a TFS bug form or any other HTML based control. 
    • Triple Click
      It’s never been easier to select a line of code from the mouse by simple triple-clicking anywhere on the line. 
    • Fix Mixed Tabs
      Some developers prefer tabs, others prefer spaces, and nobody likes mixing tabs & spaces.  This extension promotes developer harmony by warning as they are open or save a file that has a mixture of tabs & spaces.  The information bar also provides an easy way to fix the file to suit your preference. 
    • Ctrl + Click Go To Definition
      This extension gives the editor a web browser by adding clickable hyperlinks to symbols in your code as you hold down the Ctrl key.
    • Align Assignments
      This extension is useful for making your code a little more readable by aligning the assignments when you type Ctrl+Alt+] such that it takes this:

      And turns it into this:

      Please note: This may conflict with your formatting settings. E.g. in C# you will need to disable: Tools->Options->Text Editor->C#->Formatting->Spacing->"Ignore spaces in declaration statements"

    Enjoy!

     

       Daniel

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

    Free Visual Studio 2008 and .NET Framework 3.5 Training Kit

    • 2 Comments

    The Visual Studio 2008 and .NET Framework 3.5 Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio 2008 features and a variety of framework technologies including: LINQ, C# 3.0, Visual Basic 9, WCF, WF, WPF, ASP.NET AJAX, VSTO, CardSpace, SilverLight, Mobile and Application Lifecycle Management.

    Cheers

       Daniel

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

    Übungsaufgabe und Lösung zu „Get the BASICs, Visual Basic für Einsteiger und Umsteiger“, Teil 6

    • 0 Comments

    Aufgabe

    • Schreiben Sie die zwei Klassen Amateurspieler und Profispieler
    • Beide Klassen sollen ein Interface ISpieler implementieren
      • Property SpielerName
      • Property Position
      • Methode Torschiessen
    • Schreiben Sie eine Methode welche die Namen, Position und geschossenen Tooooore der Spieler ausgibt

    Lösung (1)

    Option Strict On

    Option Explicit On

     

    Module Module1

     

        Sub Main()

     

            Dim Amateur As New Amateurspieler

            Amateur.SpielerName = "Amateur XYZ"

            Amateur.Position = "Sturm"

            Amateur.Torschiessen()

     

            Dim Profi As New Profispieler

            Profi.SpielerName = "Profi ABC"

            Profi.Position = "Tor"

            Profi.Torschiessen()

            Profi.Torschiessen()

     

            Ausgabe(Amateur)

            Ausgabe(Profi)

     

        End Sub

     

        Public Sub Ausgabe(ByVal Spieler As ISpieler)

     

            Console.WriteLine(String.Format("Name des Spielers: {0}", Spieler.SpielerName))

            Console.WriteLine(String.Format("Position des Spielers: {0}", Spieler.Position))

            Console.WriteLine(String.Format("Geschossene Toooore: {0}", Spieler.AnzahlTore))

            Console.WriteLine()

            Console.WriteLine()

     

        End Sub

     

    End Module

     

    Interface ISpieler

     

        Property SpielerName() As String

        Property Position() As String

        ReadOnly Property AnzahlTore() As Integer

        Sub Torschiessen()

     

    End Interface

     

    Public Class Amateurspieler

        Implements ISpieler

     

     

        Private _Position As String

        Private _SpielerName As String

        Private _AnzahlTore As Integer

        Private _Gehalt As Double

     

     

        Public Property Position() As String Implements ISpieler.Position

            Get

                Return _Position

            End Get

            Set(ByVal value As String)

                _Position = value

            End Set

        End Property

     

        Public Property SpielerName() As String Implements ISpieler.SpielerName

            Get

                Return _SpielerName

            End Get

            Set(ByVal value As String)

                _SpielerName = value

            End Set

        End Property

     

        Public Property Gehalt() As Double

            Get

                Return _Gehalt

            End Get

            Set(ByVal value As Double)

                _Gehalt = value

            End Set

        End Property

     

        Public ReadOnly Property AnzahlTore() As Integer Implements ISpieler.AnzahlTore

            Get

                Return _AnzahlTore

            End Get

        End Property

     

     

        Public Sub Torschiessen() Implements ISpieler.Torschiessen

            _AnzahlTore += 1

            _Gehalt += 50

        End Sub

     

    End Class

     

    Public Class Profispieler

        Implements ISpieler

     

        Private _Position As String

        Private _SpielerName As String

        Private _AnzahlTore As Integer

        Private _Gehalt As Double

     

     

        Public Property Position() As String Implements ISpieler.Position

            Get

                Return _Position

            End Get

            Set(ByVal value As String)

                _Position = value

            End Set

        End Property

     

        Public Property SpielerName() As String Implements ISpieler.SpielerName

            Get

                Return _SpielerName

            End Get

            Set(ByVal value As String)

                _SpielerName = value

            End Set

        End Property

     

        Public Property Gehalt() As Double

            Get

                Return _Gehalt

            End Get

            Set(ByVal value As Double)

                _Gehalt = value

            End Set

        End Property

     

        Public ReadOnly Property AnzahlTore() As Integer Implements ISpieler.AnzahlTore

            Get

                Return _AnzahlTore

            End Get

        End Property

     

     

        Public Sub Torschiessen() Implements ISpieler.Torschiessen

            _AnzahlTore += 1

            _Gehalt += 1000

        End Sub

     

    End Class

     

    Wie in o.g. Lösung zu sehen ist stellt die Implementierung des Interfaces ISpieler in den Klassen Amateurspieler und Profispieler sicher, dass beide Klassen alle Properties und alle Methoden des Interfaces implementieren. Unschön ist jedoch, dass beide Klassen sehr viel gleichen Code beinhalten wie in dem nachfolgend skizziertem Klassendiagramm ersichtlich ist.

    Implementierung der Aufgabe mit Hilfe eines Interfaces.

    Aus diesem Grund wurden in der zweiten Lösung Teile beider Klassen in eine allgemeine Basisklasse Spieler ausgelagert. An dem neuen Klassendiagramm wird sehr schön deutlich, wie der davor doppelt vorhandene Code jetzt nur noch an einer Stelle implementiert werden muss.

    Auslagern von gemeinsam verwendetem Code in einer Basisklasse.

    Lösung (2)

    Option Strict On

    Option Explicit On

     

    Module Module1

     

        Sub Main()

     

            Dim Amateur As New Amateurspieler

            Amateur.SpielerName = "Amateur XYZ"

            Amateur.Position = "Sturm"

            Amateur.Torschiessen()

     

            Dim Profi As New Profispieler

            Profi.SpielerName = "Profi ABC"

            Profi.Position = "Tor"

            Profi.Torschiessen()

            Profi.Torschiessen()

     

            Ausgabe(Amateur)

            Ausgabe(Profi)

     

        End Sub

     

        Public Sub Ausgabe(ByVal meinSpieler As Spieler)

     

            Console.WriteLine(String.Format("Name des Spielers: {0}", meinSpieler.SpielerName))

            Console.WriteLine(String.Format("Position des Spielers: {0}", meinSpieler.Position))

            Console.WriteLine(String.Format("Geschossene Toooore: {0}", meinSpieler.AnzahlTore))

            Console.WriteLine()

            Console.WriteLine()

     

        End Sub

     

    End Module

     

    Public Class Spieler

     

        Private _Position As String

        Private _SpielerName As String

        Private _AnzahlTore As Integer

        Private _Gehalt As Double

     

     

        Public Property Position() As String

            Get

                Return _Position

            End Get

            Set(ByVal value As String)

                _Position = value

            End Set

        End Property

     

        Public Property SpielerName() As String

            Get

                Return _SpielerName

            End Get

            Set(ByVal value As String)

                _SpielerName = value

            End Set

        End Property

     

        Public Property Gehalt() As Double

            Get

                Return _Gehalt

            End Get

            Set(ByVal value As Double)

                _Gehalt = value

            End Set

        End Property

     

        Public Property AnzahlTore() As Integer

            Get

                Return _AnzahlTore

            End Get

            Set(ByVal value As Integer)

                _AnzahlTore = value

            End Set

        End Property

     

    End Class

     

    Interface ISpieler

     

        Sub Torschiessen()

     

    End Interface

     

    Public Class Amateurspieler

        Inherits Spieler

        Implements ISpieler

     

        Public Sub Torschiessen() Implements ISpieler.Torschiessen

            AnzahlTore += 1

            ' AnzahlTore = AnzahlTore + 1

            Gehalt += 50

        End Sub

     

    End Class

     

    Public Class Profispieler

        Inherits Spieler

        Implements ISpieler

     

     

        Public Sub Torschiessen() Implements ISpieler.Torschiessen

            AnzahlTore += 1

            Gehalt += 1000

        End Sub

     

    End Class

     

    P.S. Da die Frage während des Webcasts aufkam: Die Bilder wurden mit dem Klassendesigner des Visual Studios 2005 erstellt. Der Klassendesigner ist ab der Standard Version enthalten.

    Referenzen:

    Objektorientiertes Programmieren in Visual Basic
    http://msdn2.microsoft.com/de-de/library/b86b82w0(VS.80).aspx

    Class-Anweisung
    http://msdn2.microsoft.com/de-de/library/wa0hwf23(VS.80).aspx

    Vererbung in Visual Basic
    http://msdn2.microsoft.com/de-de/library/5x4yd9d5(VS.80).aspx

    Schnittstellen in Visual Basic
    http://msdn2.microsoft.com/de-de/library/28e2e18x(VS.80).aspx

    Schöne Grüße

    Daniel

Page 1 of 12 (284 items) 12345»