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)
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…
… and open the Server Properties.
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).
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.
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.
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.
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 :-)
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):
… sowie einen guten und erfolgreichen Start in das neue Jahr wünsche ich allen Lesern meines Blogs!
Festliche Grüße
Daniel Walzenbach
Hah! (We’re back ;-) ) It’s as easy as that:
Needless to say that other formatting – like Currency formatting – works as well
Check out Formatting Types on the .NET Framework Developer's Guide or SteveX Compiled - String Formatting in C# (nice cheat sheet) for more examples.
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:
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 />
ID="Label2" runat="server" Text="Name:"
Font-Bold="False" Font-Size="Small" />
<asp:TextBox ID="txtName" runat="server" />
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtName"
ErrorMessage="Bitte geben Sie einen Namen ein." />
<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"
<head><title>
Benutzerverwaltung
</title></head>
<form name="form1" method="post" action="Default.aspx" onsubmit="javascript:return WebForm_OnSubmit();" 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&t=632969108944906146" type="text/javascript"></script>
<script src="/ClientTarget/WebResource.axd?d=wFFdy1h0cE0vw88ojJditOq7o464AD3s8S-LqSeUmxk1&t=632969108944906146" type="text/javascript"></script>
function WebForm_OnSubmit() {
if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;
return true;
<span id="Label1" style="color:DarkGray;font-family:Verdana;font-size:Larger;font-weight:normal;font-style:italic;">Benutzerverwaltung</span>
<span id="Label2" style="color:DarkGray;font-family:Verdana;font-size:Small;font-weight:normal;">Name:</span>
<input name="txtName" type="text" id="txtName" />
<span id="RequiredFieldValidator1" style="color:Red;visibility:hidden;">Bitte geben Sie einen Namen ein.</span>
<input type="submit" name="btnLaden" value="Laden" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("btnLaden", "", true, "", "", false, false))" id="btnLaden" />
var Page_Validators = new Array(document.getElementById("RequiredFieldValidator1"));
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 = "";
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwLr3vKqCwLEhISFCwKct5SxA0qg7S78OUEVS+kzdJhDLF6zY2mx" />
var Page_ValidationActive = false;
if (typeof(ValidatorOnLoad) == "function") {
ValidatorOnLoad();
function ValidatorOnSubmit() {
if (Page_ValidationActive) {
return ValidatorCommonOnSubmit();
else {
ClientTarget="downlevel"
<form name="form1" method="post" action="/ClientTarget/Default.aspx" id="form1">
<span id="Label1"><i><font face="Verdana" color="DarkGray">Benutzerverwaltung</font></i></span>
<span id="Label2"><font face="Verdana" color="DarkGray" size="3">Name:</font></span>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwLr3vKqCwLEhISFCwKct5SxA0qg7S78OUEVS+kzdJhDLF6zY2mx" /></form>
Schöne Grüße
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!
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 2005Visual Studio Keyboard Shortcut Reference C# 2005Visual Studio Keyboard Shortcut Reference C++ 2005
Äußerst cool!
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:
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 ;-)
Cheers
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:
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 ;-)
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
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...
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 ;-)
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:
Additional information can be found here.
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!
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) _
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
Return _Description
_Description = value
Public Property Path() As String
Return _Path
_Path = value
Public Property Size() As Long
Return _Size
Set(ByVal value As Long)
_Size = value
Btw, if you bind the result to a DataGridView you can copy&paste from there into excel. Needo :-)
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.
The following are some HTML Editors for ASP.NET providing "Rich Text box" functionality and are definitely worth a try.
FreeTextBox >> http://freetextbox.com/
FCKEditor >> http://www.fckeditor.net/
TinyMCE >> http://tinymce.moxiecode.com/
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!
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
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 :-(
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 ;-)
Bis zur nächsten TechEd! Schöne Grüße von Daniel
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 ;-)
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:
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>
Lets start with some infrastructure and build a webservice that returns a List(Of Location) which we will use later.
Imports System.Web.ServicesImports System.Web.Services.ProtocolsImports 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
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 DoubleEnd 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>
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 datafunction 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 failsfunction 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 mapfunction 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 instancefunction 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!
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.
Ok. Eigentlich wollte ich ja schon im Bett sein aber das ist dann doch zu arg ;-)
Noch cooler ist jedoch, dass obiger Code tatsächlich lauffähig ist und folgende Ausgabe erzeugt :-)))
Kudos an Kit George! In diesem Sinne…
Nachtrag (20070913_1135)P.S.: Den Quellcode gibt's übrigens auf http://blogs.msdn.com/vbteam/archive/2007/09/06/fun-with-vb.aspx
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 :-))))
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.
Aufgabe
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()
Ausgabe(Amateur)
Ausgabe(Profi)
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()
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
Return _Position
_Position = value
Public Property SpielerName() As String Implements ISpieler.SpielerName
Return _SpielerName
_SpielerName = value
Public Property Gehalt() As Double
Return _Gehalt
Set(ByVal value As Double)
_Gehalt = value
Public ReadOnly Property AnzahlTore() As Integer Implements ISpieler.AnzahlTore
Return _AnzahlTore
Public Sub Torschiessen() Implements ISpieler.Torschiessen
_AnzahlTore += 1
_Gehalt += 50
Public Class Profispieler
_Gehalt += 1000
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.
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.
Lösung (2)
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))
Public Class Spieler
Public Property Position() As String
Public Property SpielerName() As String
Public Property AnzahlTore() As Integer
Set(ByVal value As Integer)
_AnzahlTore = value
Inherits Spieler
AnzahlTore += 1
' AnzahlTore = AnzahlTore + 1
Gehalt += 50
Gehalt += 1000
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 Basichttp://msdn2.microsoft.com/de-de/library/b86b82w0(VS.80).aspx
Class-Anweisunghttp://msdn2.microsoft.com/de-de/library/wa0hwf23(VS.80).aspx
Vererbung in Visual Basichttp://msdn2.microsoft.com/de-de/library/5x4yd9d5(VS.80).aspx
Schnittstellen in Visual Basichttp://msdn2.microsoft.com/de-de/library/28e2e18x(VS.80).aspx
"Get the BASICs, Visual Basic für Einsteiger und Umsteiger", Teil 1
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
Lösung
' 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(" +")
"Get the BASICs, Visual Basic für Einsteiger und Umsteiger", Teil 2
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².
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)
"Get the BASICs, Visual Basic für Einsteiger und Umsteiger", Teil 3
Schreiben Sie ein Programm welches mit Hilfe einer Schleife
' 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 & " ")
' zwei leere Zeilen ausgeben
' die zweite Aufgabe
' die Quadratzahlen von 0 bis 20 zeilenweise ausgibt
' Wichtig! Die Quadratzahl der Zahl 10 soll NICHT ausgegeben werden!
Console.WriteLine("Aufgabe 2")
' 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))
' die dritte Aufgabe
' einen halben Tannenbaum ausgibt
Console.WriteLine("Aufgabe 3")
For i As Integer = 0 To 13
For j As Integer = 0 To 13
If i < 11 Then
Console.Write("*")
If j = i Then
Exit For
Else
Console.WriteLine("***")
Next ' j
Next ' i
The November CTP of SQL Server 2008 is a huge step forward as we continue delivering on our Data Platform Vision for “Your Data, Any Place, Any Time.” SQL Server 2008 will bring that vision to life, and there is something in this feature-rich CTP to meet the needs of companies of all sizes. I really believe it is going to be an eye opener for a lot of people, not just in terms of the new features that will be included, but how close we are to delivering a final product with very high quality. Here a just some of the great new/improved features.
Data Collection and Performance Warehouse for Relational EnginePerformance tuning and troubleshooting are time-consuming tasks for the administrator. To provide actionable performance insights to administrators, SQL Server 2008 delivers more extensive performance data collection, a new centralized data repository for storing performance data and new tools for reporting and monitoring.
Service Broker Enhancements Getting the data to the right place at the right time is important. Service Broker Conversation Priority in SQL Server 2008 gives you greater control over the system by making it easy to configure priority rules so that the most important data is sent first and processed first.
Registered Servers EnhancementsEnhancements to the Registered Servers tool window in Management Studio include running T-SQL queries and policies against groups of servers and the ability to share a common, centrally stored, server topology (Database Engine only).
Synchronous net-changes change tracking for SQL ServerSQL Change Tracking feature provides the functionality to synchronously track changes to data in user table without the need to create triggers or modify schema of the table. Applications will be able to reliably determine what data has changed since a watermark/baseline and will be able to obtain the latest data. The feature is geared towards providing the functionality with least DML overhead.
T-SQL IntelliSenseTransact-SQL IntelliSense provides intelligent aids for Transact SQL scripting that make language references easily accessible for database developers. When coding, you do not need to leave the Database Query Editor to perform searches on T-SQL language elements or your database metadata. You can keep your context, find the information you need, insert T-SQL language elements directly into your code, and even have IntelliSense complete your typing for you. This can speed up software development by reducing the amount of keyboard input required and minimize references to external documentation.
Declarative Management Framework (DMF) EnhancementsEnhancements to DMF include more expressive conditions (including support for common functions, T-SQL, and WMI queries), more robust target set filtering, custom messages for policies, and the inclusion of best practice policies.
Geo-spatial SupportSQL Server 2008 delivers comprehensive geo-spatial support. The new GEOGRAPHY and GEOMETRY data types provide spatial data support for location-aware applications. These types can be used to store locations, as well as paths and regions in space, and provide a rich set of functionality for comparing and manipulating these objects. Use the GEOGRAPHY type when working with latitude and longitude coordinates in a true round-earth model; use GEOMETRY when working in projected planar surfaces, as well as naturally planar systems such as interior spaces. These types are supported by new spatial indexes, which provide for fast execution of queries involving spatial data. The query optimizer has been enhanced to build-in knowledge of spatial indexes and types, so that appropriate cost-based plan decisions can be made.
Analysis Services Query and Writeback Performance (FITS)New MOLAP-enabled write-back capabilities in SQL Server 2008 Analysis Services remove the need to query ROLAP partitions. This provides users with enhanced writeback scenarios from within analytical applications without sacrificing the traditional OLAP performance.
Robust Report Server PlatformReports can easily be delivered throughout the organization with simplified deployment and configuration. This enables users to easily create and share reports of any size and complexity.
Integration Services - Lookup EnhancementsThe need to perform lookups is one of the most common extraction, transformation, and loading (ETL) operations. This is especially prevalent in data warehousing where fact records must use lookups to transform business keys to their corresponding surrogates. SSIS increases the performance of lookups to support the largest tables.
Analysis Services MDX Query Optimizer - Block ComputationBlock computations provide a significant improvement in processing performance, enabling users to increase the depth of their hierarchies and complexity of the computations.
Analysis Services Aggregation DesignSQL Server 2008 drives broader analysis with enhanced analytical capabilities and with more complex computations and aggregations. The AS Aggregation Design improvement exposes Aggregation Design objects in SQL Server BI Dev Studio and SQL Server Management Studio and provides tools for users to better work with these aggregation designs. In addition, an advanced view in the new Aggregation Design tab of the cube editor provides the ability for an advanced user to view and manually edit individual aggregations within an aggregation design.
Analysis Services Cube DesignNew cube design tools help users streamline the development of the analysis infrastructure, enabling them to build solutions for optimized performance. The AS Cube Design improvement introduces a new Cube Wizard which helps users create better cubes in fewer steps. The new wizard focuses on having the user answer a few questions to create leaner cubes that better targets their needs. It also unblocks the previously difficult scenarios of creating a cube a cube based on a single, de-normalized table and creating a cube containing only linked dimensions.
Reporting Services Scale Engine and Robust Server Fit and FinishA reengineered memory management and scalability infrastructure lays a solid foundation of scalability capability to enterprise customers.