Comparing LINQ to SQL vs the classic SqlCommand
When you are coming from using SqlCommand and SqlConnection is difficult to move to another library for your database needs. For those people still in the limbo to make the decision to move to another DAL, here is a comparison to help you see the light or to move away for ever.
How to do a select query using SqlCommand:
1: SqlConnection myConnection = new SqlConnection(@"Data Source=PROG-3407\SQLEXPRESS;Initial Catalog=Demo;Integrated Security=True;Pooling=False");
2:
3: string sQuery = "SELECT * FROM Table1";
4:
5: SqlCommand myCommand = new SqlCommand(sQuery);
6: myCommand.Connection = myConnection;
7:
8: myConnection.Open();
9:
10: SqlDataReader dataReader = myCommand.ExecuteReader();
11:
12: while (dataReader.Read() == true)
13: {
14: string sID = dataReader[0].ToString();
15: string sName = dataReader[1].ToString();
16: string sCity = dataReader[2].ToString();
17:
18: MyData dat = new MyData()
19: {
20: ID = Int32.Parse(sID),
21: Name = sName,
22: City = sCity
23: };
24: myDataCollection.Add(dat);
25: }
26:
27: GridView1.DataSource = myDataCollection;
28: GridView1.DataBind();
29:
30: dataReader.Close();
31: myConnection.Close();
And now a select query in LINQ to SQL
1: Table1DataContext dataContext = new Table1DataContext();
2:
3: var all = from p in dataContext.Table1s orderby p.City select p;
4:
5: GridView1.DataSource = all;
6: GridView1.DataBind();
Pretty short isn’t it?, the select statement is inline with a little help from intellisense.
Insert in SqlCommand
1: using (SqlConnection myConnection = new SqlConnection(@"Data Source=PROG-3407\SQLEXPRESS;Initial Catalog=Demo;Integrated Security=True;Pooling=False"))
2: {
3: string sQuery = "INSERT INTO Table1 (Name,City) values(@Name,@City)";
4:
5: SqlCommand myCommand = new SqlCommand(sQuery);
6: myCommand.Connection = myConnection;
7:
8: myConnection.Open();
9:
10: myCommand.Parameters.AddWithValue("@Name", TextBoxName.Text);
11: myCommand.Parameters.AddWithValue("@City", TextBoxCity.Text);
12:
13: myCommand.ExecuteNonQuery();
14: }
Insert in LINQ in SQL
1: Table1DataContext dataContext = new Table1DataContext();
2:
3: Table1 row = new Table1()
4: {
5: City = TextBoxCity.Text,
6: Name = TextBoxName.Text
7: };
8:
9: dataContext.Table1s.InsertOnSubmit(row);
10: dataContext.SubmitChanges();
Hope this helps
Cheers
Al
How to extend Bing Maps Silverlight with an elevation profile graph – Part 1
Introduction
One of the things I found missing in the current Bing Maps product is the possibility to create an elevation surface profile of routes. Perhaps this feature may not seem much on demand but actually affects more people than expected. Think for example about sports events like marathons and cycling races: to see a preview of the elevation profile of the trail would be of great benefit to the participants. But even if you're just simple hikers you might want to know what is the difference in level of your walking or bicycle trip to better understand the effort that it would entail.
So why not try to create this feature from scratch using the Bing Maps Silverlight Control? In this first part we will see how to extend the Bing Maps Silverlight Control by adding new commands to the navigation bar, how to create a route based on a start and end address or by clicking directly on the map and how to obtain elevation data of the route. In the second part we will briefly deal with details about the implementation via threads of the elevation data retrieval and we will show how to add some interactivity to the Chart control of the Silverlight toolkit.
I assume that the reader is already familiar with the basics related to the use of Bing Maps in Silverlight. If not so, I would like to suggest reading the first chapters of the SDK guide or at least the "Getting started" paragraph of the following interesting article already published on SilverlightShow.
In the second part a link to the live demo and to the source code will be made available; in the meantime you can watch a video here of an early beta.
The User Interface
What I wanted to do was to add this type of functionality to the Bing Maps Silverlight Control integrated with the existing interface. With this aim in mind I added 2 items to the navigation bar of the Bing Maps Silverlight Control as you can see on the following image, where the items “Route Profile“ and “Arbitrary Profile” have been added.
A click on “Route Profile” item opens a popup window which allows choosing 2 options:
- Building the route by inserting pushpins on the map
- Building the route providing a start address and an end address
With the first option you can put a series of pushpins on the map with a simple click of the mouse on the map; a double click starts the route calculation and, after that, the generation of the elevation profile graph. The second option considers first the geocoding of the start and end address of our route and then proceeds in the same way as the first option.
A click on “Arbitrary Profile”, instead, allows you to draw polylines directly on the map; even here a double click of the mouse triggers the generation of the route and the subsequent creation of the elevation profile graph.
The graph offers some kind of interactivity in the way that you can select and move 2 cursors over the points of the profile and see some conclusive data like the average elevation with regard to the portion of the profile between the two cursors.
Main points of interest
An interesting element is the description of how it was possible to add new commands to the navigation bar of the Bing Maps Silverlight Control without giving the impression of a last minute addition but of a natural integration. Another point which might be of interest for the reader is the retrieval of the elevation data and the subsequent creation of the profile graph; during the process the user is allowed to interact with the map thanks to the use of threads. Finally, the possibility to interact with the Chart control can offer some ideas for further improvements.
How to How to add items to the navigation bar of the Bing Maps Silverlight Control
The first thing I thought of doing to achieve this objective was to understand how the navigation bar was made. Obviously to better understand that I needed to see the XAML code which generates the navigation bar; but, how to get the XAML code? The setup of the Bing Maps Silverlight Control SDK (which can be downloaded at the following link ) installs two DLL files on your pc : “Microsoft.Maps.MapControl.dll” and “Microsoft.Maps.MapControl.Common.dll”. They contain all the assemblies needed in order to use the Silverlight Bing Maps Control in your applications. While I was looking inside the installation folders in order to find an inspiration at some point I remembered reading somewhere on the web that one could just open the DLL in a text editor and see the XAML code in plaintext. Indeed, if you open the "Microsoft.Maps.MapControl.dll" file and scroll down the content, at a certain point you see a large portion of XAML code and there is where you have to investigate. If you look at the code below which is the part describing how it is organized the superior portion of the navigation bar:
1: <StackPanel Grid.Row="0" Grid.Column="3" Orientation="Horizontal" x:Name="HorizontalPanel">
2: <StackPanel Orientation="Horizontal" x:Name="HorizontalLeftPanel">
3: <navigation:CommandRadioButton x:Name="RoadStyleButton" />
4: <navigation:CommandRadioButton x:Name="AerialStyleButton" />
5: </StackPanel>
6: <navigation:CommandSeparator />
7: <StackPanel Orientation="Horizontal" x:Name="HorizontalRightPanel">
8: <navigation:CommandToggleButton x:Name="LabelsButton" />
9: </StackPanel>
10: </StackPanel>
You see that there is a StackPanel (called “HorizontalPanel”) which contains two other StackPanels called respectively “HorizontalLeftPanel” and “HorizontalRightPanel”. Inside them, there are the buttons you are used to clicking when you interact with the Bing Maps Silverlight Control, i.e. “Road”, “Aerial” and “Labels”.
So, if you want to add two other commands as in the first image above, in principle you just have to create two instances of the type CommandRadioButton (which is in the assembly Microsoft.Maps.MapControl.Navigation) and add them to the “HorizontalPanel” as children controls. But the reality is somewhat more complicated than just described. In order to add these controls you have to wait for the completion of the initialization phase of some components. This phase, without going too much over details, can be regarded as made up of 2 steps. A first step where the ForegroundMap Control is loaded; this is the control which displays amongst other the map navigation bar on the map. A second step where the navigation bar is loaded. Only after these two phases you can add your controls. In practical terms first you have to add an EventHandler to the TemplateApplied EventHandler of the ForegroundMap Control. When the event is triggered it means that the NavigationBar has been instantiated and you can add another EventHandler this time to the TemplateApplied EventHandler of the NavigationBar. Once this last event is triggered you can add your controls to the NavigationBar. The portion of code below realizes what I have just described.
1: ...
2: private CommandRadioButton routeBtn = new CommandRadioButton();
3: private CommandRadioButton freeProfileBtn = new CommandRadioButton();
4: ...
5: public MainPage()
6: {
7: InitializeComponent();
8: ...
9: ElevationChartMap.MapForeground.TemplateApplied += new EventHandler(MapForeground_TemplateApplied);
10: ...
11: }
12:
13: void MapForeground_TemplateApplied(object sender, EventArgs e)
14: {
15: ElevationChartMap.MapForeground.NavigationBar.TemplateApplied += new EventHandler(NavigationBar_TemplateApplied);
16: }
17:
18: void NavigationBar_TemplateApplied(object sender, EventArgs e)
19: {
20: NavigationBar navControl = ElevationChartMap.MapForeground.NavigationBar;
21:
22: navControl.HorizontalPanel.Children.Add(routeBtn);
23: navControl.HorizontalPanel.Children.Add(freeProfileBtn);
24: }
Creating the route with the “Route Profile” option
For the creation of the route either giving start and end address or inserting some markers on the map I used part of the code samples available on Keith Kinnan’s Blog and presented during the PDC09. I don’t want to repeat what has been already very well explained at the links above so I will stick to a brief description.
First of all, you have to create two service references, the Geocode service and the Route service:
https://staging.dev.virtualearth.net/webservices/v1/routeservice/routeservice.svc?wsdl
https://staging.dev.virtualearth.net/webservices/v1/geocodeservice/geocodeservice.svc?wsdl
Don’t forget the final postfix “?wsdl” which is missing in the related paragraph (“Calculating a Route Using Bing Maps Web Services “) of the SDK Guide version 1.01.
With the first Service you obtain the coordinates of the user location inputs; these coordinates can be then provided to the Route Service to calculate the route. Since Silverlight uses an asynchronous model all the requests to the Services above have to be asynchronous. For instance, after you inserted the start and end address of your route, two asynchronous calls to the Geocode Service are made. To catch them, an EventHandler to the GeocodeCompleted event has been added. Inside this EventHandler we keep track of how many times it was crossed; if it has been twice it means that both start and end address have been elaborated and then it is possible to make the request to the Route Service, where another EventHandler has been added to intercept the CalculateRouteCompleted event. In this EventHandler the result of the calculation is checked and if it is Ok the Polyline representing the route is drawn. In particular an object of type MapPolyline is instantiated and the points in geographic coordinates resulting from the calculation are added to its "Locations" property. This object is then added to a MapLayer which represents a layer over the map and allows to position UI elements according to geographic coordinates. The code below illustrates what I have described.
1: double dist = e.Result.Result.Summary.Distance;
2: Color routeColor = Colors.Blue;
3: SolidColorBrush routeBrush = new SolidColorBrush(routeColor);
4:
5: //Add the Polyline for the route
6: MapPolyline routeLine = new MapPolyline();
7: routeLine.Locations = new LocationCollection();
8: routeLine.Stroke = routeBrush;
9: routeLine.Opacity = 0.65;
10: routeLine.StrokeThickness = 5.0;
11: foreach (Location loc in e.Result.Result.RoutePath.Points)
12: {
13: routeLine.Locations.Add(loc);
14: }
15: profileLayer.Children.Add(routeLine);
“Arbitrary Profile” option: how to allow the user to draw lines directly on the map
The “Arbitrary Profile” option gives the user the chance to draw a completely arbitrary polyline with subsequent mouse clicks; you can either follow the profile of a road or click on whatever you want. A double click ends the drawing mode and launches the generation of the elevation profile graph. To do that two EventHandlers have been added to the Map Control in order to intercept the mouse click and double click on the map. In case of a single click, the ViewportPoint of the MouseEventArgs object is evaluated and the result is added to the Locations Collection of a MapPolyline previously added as a child UI element to the same MapLayer used for route showing.
1: ...
2: private MapPolyline arbitraryProfilePolyline;
3: ...
4:
5: void ElevationChartMap_MouseClick(object sender, MapMouseEventArgs e)
6: {
7: if (myProfileModeMap.EnableArbitraryProfileMode == true)
8: {
9: arbitraryProfilePolyline.Locations.Add(ElevationChartMap.ViewportPointToLocation(e.ViewportPoint));
10: }
11: ...
Summary
In this first part we have explored some “internals” of the navigation bar of the Bing Maps Silverlight Control and we have given some advice on how to create routes using Geocoding and Route Services and on how to draw lines on the Map and obtain the geographics coordinates of its points. In the next article we will see how to obtain elevation data for the routes and the arbitrary paths we created and how to customize the Chart Control of the Silverlight Toolkit for the needs of this specific application. You will be also able to try a live demo and download the source code.
Cloud Event Processing: CEP in the Cloud
jCore: Open Source Multisite CMS
jCore is an open source Content Management System (CMS) build using PHP and MySQL. It can power multiple websites, enabling you to keep CMS software up to date and fix bugs for all websites from a single location.

jCore has two main systems, jCore Server – which holds all the libraries and modules, and jCore Client – which is the stripped version of the core system that install with each website. You don’t really need to install jCore server, just copy the files in a public place so that all you websites can access it.
jCore allows designers to easily create custom look & feel of their website by simply adding new blocks (DIVs) from the admin area and apply any style (CSS) or script (jQuery). The developer on the other hand can easily create new Modules to extend the site’s functionality.
Features
- Custom Look & Feel with CSS/JavaScript
- Multilanguage Support
- Multiple Menus
- Manage your site’s content with a WYSIWYG editor and attach files/pictures to them
- Create submit forms with custom fields and store or send values trough email
- Extend your site with new functionality like Photo Gallery or a File sharing module and so on
- Include posts, modules, blocks, forms and other are of your site in your posts/blocks contents
- Keep your readers up to date with RSS feeds
- Easily place ad codes / banners on your site and earn money
- Manage your site members or send out mass emails to let them know about news
- SEO Friendly Links
- Custom 404 Error Page
Developed by Istvan Petres; jCore is available for download under GNU General Public License. You can find further information, demo & download on jCore Website.
Similar Posts:
- Pligg – Social Publishing CMS
- TomatoCMS: CMS Powered By Zend, jQuery and 960 Grid System
- GalleryCMS: Free CMS For Managing Photo Galleries
- Open Atrium – Open Source Intranet Package Powered by Drupal
- List of Free Web Based HTML Editors For Your CMS Project
You can also stay updated by following us on Twitter, becoming a fan on Facebook or by subscribing to our FriendFeed.
“Going Mobile” at 360|Flex
I'm really looking forward to going to 360|Flex. When I've gone to conferences in the past, I've taken my laptop along, and this conference will be no exception. However, my plan is to only use my laptop during the hands-on...Summertime in the Philippines and the Livin’ Ain’t Easy
Summertime in the Philippines and the Livin’ Ain’t Easy
Text-To-Speech in Silverlight Using WCF
Back in February, I wrote a blog post showing you how to, using Silverlight 4 OOB (out of browser) with elevated trust, access system devices; including how to use the SAPI.SpVoice API through the new Silverlight 4 COM Interop feature to implement text to speech. The biggest problem to that approach is that it will only work on the Windows platform.
So, I started thinking to myself, that the real purpose behind Text-To-Speech isn’t just the cool factor, but it is accessibility for impaired users. I have been doing web development for nearly a decade, and I have always been conscious about web users with impairments that may make viewing or navigating my websites more difficult. Text-To-Speech isn’t very helpful if it will only work in a fully trusted out of browser Silverlight 4 application on a Windows machine. So instead, lets create a Text-To-Speech solution that will work inside the browser, on any browser, on any machine. And heck, I want this to be in Silverlight 3.
Lets get started by creating a new Silverlight 3 application, and be sure to include a web project as well.
Right click the web project and add a reference to the System.Speech.dll.
Next, lets right click the web project and click Properties –> Web and set the specific port number to your liking, I set mine to 1914. This will come in handy when we create our WCF service.
Now we need to create the WCF service that will take our text and send it back as a WAV stream, so go ahead and right click the web project and select “Add New Item”. From this list add a new WCF service and name is SpeechService. Now this is important; when you have created your WCF service an endpoint is created for you in the Web.config file. You need to change the binding of the endpoint to basicHttpBinding. Silverlight only works using basicHttpBinding, and will not create the ServiceReferences.ClientConfig file properly if you do not do this.
Now, lets add an OperationCOntract to your WCF services interface called Speak that returns a byte[], and takes a string parameter.
[ServiceContract]
public interface ISpeechService
{
[OperationContract]
byte[] Speak(string textToSay);
}
The implementation of this method will look like the following:
public byte[] Speak(string textToSay)
{
SpeechSynthesizer ss = new SpeechSynthesizer();
MemoryStream ms = new MemoryStream();
ss.SetOutputToWaveStream(ms);
ss.Speak(textToSay);
return ms.ToArray();
}
The next thing we need to do is create our UI in Silverlight. Here is what mine looks like.
<Grid x:Name="LayoutRoot">
<StackPanel>
<TextBox x:Name="_txtTextToSay" />
<Button Content="Speak To Me" Click="Button_Click" />
<MediaElement x:Name="_audioPlayer"/>
</StackPanel>
</Grid>
Create an event handler for your button. Next add a service reference to your SpeechService in your web project.
The next part is somewhat complicated and time consuming. You have to write your own WAVV decoding class that takes the byte array that is return from the service and converts it to a System.Windows.Media.MediaStreamSource. Luckily for you, I already did this for you with the help of some resources on MSDN. In the button’s event handler add this code:
private void Button_Click(object sender, RoutedEventArgs e)
{
SpeechServiceClient client = new SpeechServiceClient("BasicHttpBinding_ISpeechService");
client.SpeakCompleted += (o, ea) =>
{
WavMediaStreamSource audioStream = new WavMediaStreamSource(new MemoryStream(ea.Result));
_audioPlayer.SetSource(audioStream);
};
client.SpeakAsync(_txtTextToSay.Text);
}
Basically what this does is uses the WavMediaStreamSource class I created that inherits from MediaStreamSource, takes the byte[] returned from the SpeechService and converts it back to a stream, then is passes it off to my WAV decoding classes, which is used as the source for the MediaElement responsible for playing the audio.
All that is next is to build your solution and start making your Silverlight applications more accessible.