SQL Azure Connection error “Cannot connect to <servername>" Client with IP Address is not allowed to access server: Error 40615

If you have been using the SQL Azure Portal for creating SQL Databases and connecting to them from your SQL Server Management Studio, you would have realized the ability to query the Azure Cloud Databases from within the management studio.  While this provides great opportunities in terms of relation capabilities and accessibility over the Cloud, there has been a recent upgrade to SQL Azure and in that process there has been a Firewall Support added to the SQL Azure Portal access.

Specifically when you try to connect to SQL Azure, you would face the error

Cannot connect to <sql azure server name>

Additional Information

Cannot open server <servername> requested by the login.  Client with IP Address "<your IP Address>” is not allowed to access the host server.

Login failed for user ‘<username>’. (Microsoft SQL Server, Error: 40615)

As the error message indicates, the SQL Azure Portal has declined access to the portal for your IP Address.  This specific filtering helps companies protect their data hosted in the cloud from access by just any host.  This allows companies to restrict the access to a specific set of hosts such that they do know that those are safe.

As a result, your existing applications / querying from SQL Server Management Studio might just fail.   Note that by default no IP’s are allowed to access your server.

Also, there has been a change in the way the server is accessed as well as the credentials specified.  Lets see them step by step.

Steps to enable IP Access in the SQL Azure Portal

Visit the SQL Azure Portal at https://sql.azure.com and sign-in with the LiveID that you used to create the SQL Azure database(s)

Click on the Project name to open the Server Administration Page

You will find the Server Name, Administrator username and Server Location details specified.  You would require these when connecting to the SQL Azure database from your Management Studio.  Note that the server name is no longer <servername>.ctp.database.windows.net and just simply <servername>.database.windows.net

You would also find the databases listed under the Databases tab and additionally you would find the “Firewall Settings” tab.  Click on the “Firewall Settings” tab you will find a screen as below:-

image

Check the “Allow Microsoft Services access to the server” check box.  The page posts and then adds a “MicrosoftServices” Record Name as below

image

Click on the “Edit Record” to open up “Custom Firewall Settings” window that lists your IP address as well.  You can also specify a range in case you want to.  Once you have typed the IP Address, click “Submit”  (Note that if you dont have an IP Address range, you would have to type your actual IP Address in the bottom textbox after the “to” which means the top one is 0.0.0.0 to <IP Address you specified>.

You can add more IP Addresses by clicking on “Add Record” button and repeating the above steps. Once you do this, you would be able to access the SQL Azure database from SQL Server Management Studio.

Steps to access the SQL Azure Database using Management Studio

I had already written on this, in my earlier post  that you can check.  But, in the interest of folks who have patiently read this post from the beginning, I am repeating the steps below

Open SQL Server Management Studio

Dismiss the default login window that comes up (a temporary work around)

Click on “New Query” and type the credentials.  The servername is “<servername>.database.windows.net” and the Login is simply <username> and not username@servername as in the past.  Click on “Options” to specify the Database that you created in SQL Azure.  Otherwise, the default would connect to Master.  Once you enter the password in the “Login” tab and click “Connect” you should be able to connect to the SQL Azure database.

If you get any error, check if you had dismissed the initial login prompt and clicked on “New Query” in the Management Studio.

Cheers !!!

Visual Studio 2010 Beta 2 – a first look at the UI and Web Development

Visual Studio 2010 Beta 2 is out and has a slick new UI.  Also, this Beta has most of the features that would ship with the final version compared to the earlier Beta.  Note that while new features might be added, there are chances that some of the features demonstrated here may also not be a part of the final release.  But, for now, lets examine the current Beta 2.  The first thing you would notice and probably like, is the UI enhancements.  Herebelow, is the launch screen.

image

Also, the start page has been modified to accommodate more useful things.  The good thing is that you can completely customize the Start Page since it is a XAML based UI.  You can find the start page itself as a Project at C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\StartPages once you install the Beta.  You can change it to reflect your organization specific templates, document repositories etc.,  Optionally you can even turn it off permanently, or, upon opening a project, using the checkbox options in the bottom left.

image

Now, with respect to web development, there are tons of enhancements.  In fact many of the actual web enhancements are figuring in this Beta release and exploring them would require individual blog posts that I would be writing in future.  For a complete list of feature walkthroughs, please visit the MSDN website http://msdn.microsoft.com/en-us/vstudio/dd441784.aspx (and by the way you would realize that the MSDN Website has been re-launched as well with the new UI for easier navigation)

The first thing I did was to explore the “File – New – Project – ASP.NET Web Application” template and create a new web project.  This provides a web template with a default Home Page and About Us page that you can use as-is / customize and get started with a skeleton layout immediately.  The default UI without any work, when run, looks as below:-

image

Other thing to notice is that, by default jQuery 1.3.2 library is included in the Scripts folder, not to mention, the intellisense support for jQuery that has been there right from VS 2008 SP1.  There you had to manually install the docs as well as the jQuery library.  Now, it all comes automatically.

Web.Config file Simplified

Over the years, with ASP.NET AJAX, Data Source provider, IIS 7 configuration, the Web.Config grew extremely unmanageable and working with that would require real patience.  In this release, the Web.Config file has been minified or simplified that it just contains 4 – 5 lines of configuration.  Note that, this is when you select “Empty ASP.NET Web Application” template.  The default “ASP.NET Web Application” template still has entries corresponding to Membership, Roles, Authentication etc., since this is basically a fully functional website with users, roles as well as membership database with default entries (remember “Website Administration” screen in the ASP.NET 2.0 days)

There are much more web related features that I will be covering in the future posts, but for a high level overview, check http://msdn.microsoft.com/en-us/library/ee532866(VS.100).aspx and http://www.asp.net/learn/whitepapers/aspnet40/ 

You can download Visual Studio 2010 Beta 2 from http://www.microsoft.com/visualstudio/en-us/products/2010/default.mspx or if you are an MSDN Subscriber from the MSDN Download Center.

Cheers !!!

FileUpload in UpdatePanel, ASP.NET, like Gmail

Earlier, I had written this post on how you can accomplish using FileUpload control in UpdatePanel since by default it wasn’t supported.  The post seems to have helped many and keeps being the most visited one.  However, with the new release of Ajax Control Toolkit (v 3.0.30930) released specifically for .NET 3.5 SP1 (with Visual Studio 2008 SP1), there are couple of new controls.  One of them is the AsyncFileUpload control.

Thanks to the codeplex community which keeps getting better and better with time, the Ajax Control Toolkit has grown into one of our largest community contributed controls for ASP.NET with about 43 controls that help in accomplishing rich user experiences in ASP.NET Websites.

The AsyncFileUpload is one simple way of accomplishing what I had written earlier using PostbackTrigger, the regular FileUpload control etc.,  To be able to use the AsyncFileUpload Control, you must have the latest version of AjaxControlToolkit installed.  The other pre-requisites are obviously NET 3.5 SP1 and Visual Studio 2008 SP1 (or the free Visual Web Developer Express Edition)

You can download the pre-requisites from the respective links above.  For downloading the AjaxControlToolkit, visit the CodePlex site.  You can download just the binary files or the Source files as well, if you require to modify.  The Script Files is useful if you want to just work with the client side scripts and not use the server controls.

Once you have downloaded, you would need to add them to Visual Studio or VWD.

1. Open Visual Studio and create a new webapplication or website.  Click to open the ToolBox

2. Right Click and select “Add Tab”

3. Provide a name say “Ajax Control Toolkit”

4. Right Click the newly created tab and select “Choose Items”

5. Click on the “Browse” button in the file dialog that opens and browse to the place where you downloaded the AjaxControlToolkit binaries

6. Typically I would put them under C:\Program Files\Microsoft ASP.NET for consistency.

7. Select the AjaxControlToolkit.dll and it would list all the new controls.

8. Click “Ok” to add all the controls.

9. You should now see under the newly created toolbox tab these controls.

Once you are done with above, create a simple Default.aspx page in the application you created and drop the Script Manager control into your webform.  Next add an UpdatePanel with ContentTemplate.  Inside the ContentTemplate, add the AsyncFileUpload control into the webform as well as a button and 2 labels for the uploading and displaying messages respectively.  The markup looks something like below

<form id="form1" runat="server">
   <div>
       <asp:ScriptManager ID="ScriptManager1" runat="server">
       </asp:ScriptManager>
       <asp:Image ID="img1" runat="server" ImageUrl="~/Images/spin2.png" />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
           <ContentTemplate>
               <cc1:AsyncFileUpload ID="AsyncFileUpload1" runat="server" UploaderStyle="Modern" ThrobberID="img1"  />
       <br />
       <asp:Button ID="btnUpload" runat="server" Text="Upload"
           onclick="btnUpload_Click"   />
           <br />
           <asp:Label ID="Label1" runat="server" /> 
           <br />
           <br />
         </ContentTemplate>
       </asp:UpdatePanel>
       <br />
       <asp:Label ID="Label2" runat="server" />
   </div>
   </form>

Also, you can see that I have added an asp:Image pointing to a spin image that is specified as the ID for ThrobberID in the AsyncFileUpload definition.  This is optional but nice to have since this would display the throbber icon while uploading takes time.

Once you are done, you would need to define the action in the codebehind or in the script

protected void Page_Load(object sender, EventArgs e)
      {
          Label2.Text = DateTime.Now.ToString();
      }

      protected void btnUpload_Click(object sender, EventArgs e)
      {
          AsyncFileUpload1.SaveAs(Server.MapPath((AsyncFileUpload1.FileName)));
          Label1.Text = "You uploaded " + AsyncFileUpload1.FileName;
      }

Notice, the Label in the Page_Load event is just to indicate that indeed the operation happened asynchronously since the time that is displayed initially doesn’t change once you click on Upload button. 

Try running this and you will find that the whole operation happens asynchronously without a full page reload.  Note that, you would need to still put the AsyncFileUpload control inside UpdatPanel for this behaviour.  Otherwise, it would behave like a regular postback control.

You can download the sample code from

Cheers !!

Taking your Northwind Database to SQL Azure and binding it to an ASP.NET Grid View – Part II

In the previous post we had examined on getting access to SQL Azure, creating your first database, accessing it with SQL Server Management Studio and then migrating the Northwind database schema to SQL Azure using the SQL Azure Migration Wizard Beta.

As explained earlier, the SQL Azure Migration Wizard migrates the schema of your database after tuning it for working with SQL Azure.  However, we would still need to migrate the Data to our SQL Azure Server.  At the moment, the step I took was to open the instnwnd.sql script in SQL Server Management Studio (SSMO) and copy the Insert statements alone to execute.  Note that, you cannot run all the scripts directly onto the SQL Azure portal like I explained earlier due to the limitations / formats supported currently in SQL Azure. 

To begin with, open “C:\SQL Server 2000 Sample Databases” folder (the default location where Northwind and pubs sample database gets installed) and double click on the instnwnd.sql script.  It opens up in SSMO.   Examine the scripts and navigate to the portion where the INSERT statements begin.  I took the portion and put it up as a single insert script.  You can download the script  from the link below:-

 

Running the scripts from SQL Server Management Studio

As explained in my previous post, open SSMO and cancel the initial login prompt.  Click on “New Query” and specify the server name as the fully qualified Azure Server name i.e. <YOURSERVERNAME>.ctp.database.windows.net, specify the user name, password.  Click on “Options” and specify “Northwind” at “Connect to database” option.  Click “Connect”.  It should be able to connect provided you have specified the path, username, password etc., correctly and created the “Northwind” database as per the previous post.  There will be a small error prompt that comes before opening the Query window, as below.  You can ignore that and click “ok”

 

image

 

Once you are in the SqlQuery1.sql screen you can check if the database is created and the tables are there by running  a bunch of few queries as below:-

SELECT * FROM Products

SELECT * FROM Orders etc.,

You will get blank result sets since we haven't migrated the data yet.

Double lick to open the insertnwnddata.sql script downloaded in the first step.  It would open in a new sql window.  Copy paste the script into the first window we got once we connected to the Azure Database.  If you get a connection error.  Try reconnecting using the “New Query” option as explained above.  If all is good, you should be able to execute the scripts.  Once the scripts are successful, you can test if the data is migrated, by again running the SELECT statements above.  They should now list data.   If there is an error, try running the individual INSERT statements for each table to verify which table has the issue.

Once this is done, we are all set to bind this data to our ASP.NET Page.

Binding the SQL Azure database to ASP.NET Page

Open Visual Studio 2008 and create a web application project.  In the Default.aspx page, drag and drop a GridView control and use the GridView’s wizard to connect to your local Northwind database.  Pick the Products table and chose the columns you want to display and complete the steps.  You may want to enable paging to avoid all data shown in the same page.

The above steps should add a GridView, a SQL Data Source to the page.  Once you run the website, it should display the Products table record with the columns you chose to display.  So far, we have bound the local database.  We however, intended to bind it to SQL Azure database that we have created.

Binding the GridView to the SQL Azure Database Table

If you thought this is another big process, you might be in for a surprise.  Visit the SQL Azure portal (https://sql.azure.com) sign-in with your credentials that you used to create the token/database etc., Click on the “Manage” link that comes in the right of the Configuration Page that you get once you sign-in.  The next screen lists all the databases created.  Click on the “Northwind” database radio button to select it.   Click on “Connection Strings” in the bottom (the one in the top gives the connection string for master, so click on the “Connection Strings” button below the grid that displays the databases.   You should get a popup with 3 different connection strings targeting different data access methodologies.  Chose the first one (Click on “Copy to Clipboard”) corresponding to the entry for ADO.NET (the first one). 

In Visual Studio, open the web.config file of the site that we created earlier and visit the connectionstrings setting.  If you had followed the wizard steps, it would have entered a connection string over here, that corresponds to your local database server.

Replace the connection string with the one copied here.  Note, you need to update the password that you used instead of “mypassword”.  Also, remove the trailing semicolon at the end after password. 

If you have done all the steps properly, you should be able to run the solution now and without any other change, the data that is bound to your grid view should display the same as it did when you initially bound it to the local database.  You can try paging / sorting etc., to see if all works fine. 

So, practically, we just had to change the connection string to be able to access the database on the SQL Azure Server.  From a developer’s perspective, the data access technique, binding, control and configuration remains unchanged.

That’s it for this series.  There are quite a lot of steps that I had listed over the last 2 posts.  You may want to check every point if you are facing any issue at any stage.

Cheers !!!

Taking your Northwind Database to SQL Azure and binding it to an ASP.NET Grid View – Part I

SQL Azure is the latest buzz around Cloud Computing and the ability to take relational database to the cloud as is, is something most would welcome compared to the earlier model of ACE (Authority, Container, Entity) that was there when SQL Azure was SSDS.   Well, like others, I also got interested and wanted to explore the SQL Azure.  SQL Azure is currently in CTP and offers token based access.  I would briefly outline the steps here on getting the SQL Azure Token, although Jim O’Neil has a nice post on this

Visit SQL Azure Registration at Microsoft Connect

Sign in with your Live ID (Passport, Hotmail, MSN, Live)

Fill in the details and submit the form

You should receive the invitation code in an email from an alias “SQL Azure Talk” or something similar (note this may take from a day to a week until the CTP is available)

Visit https://sql.azure.com

Fill in the Invitation Code received in the email

You will be directed a page similar to below

image

Click on the “Manage” link in the right. It will take you to a page as below:-

This page is where you can create / delete databases as well as get the connection string etc.,

image

In the top of this page you will also see “Connection Strings” , “Reset Password” icons and also the Server Name, User Name that you chose, and the location where the database is hosted.

You can click on “Create Database” to specify a new Database table name (that’s all you can do, you cannot create tables from here, just the database)

As you can see, I have created a few databases except master which is the default database.  You can chose an individual database and then click on the “Connection Strings” icon in the bottom (currently disabled) to get the specific connection string for the database you created.

Now, this is the first step towards getting access to SQL Azure Services.

Next, the big question you might have is how do I create tables, procedures etc.,  The MSDN Sample documentation provides you the instructions on creating a basic database with a single table.  However, you might want to create / import a relational database such as Northwind with more tables etc.,  The trick here is that not all data formats are supported, particularly the deprecated ones such as ntext, image etc., at least at the moment and you can’t just go ahead and run the DB Scripts against SQL Azure to create the database and tables.  Lets examine one by one on the steps to access SQL Azure Tables in SQL Server Management Studio, Getting a script that can be executed on SQL Azure, Uploading data to SQL Azure and finally binding it to GridView

Accessing SQL Azure Tables in SQL Server Management Studio

SQL Server Management Studio (SSMO) is probably the most favourite tool used for querying, running scripts etc.,  You can download SSMO for SQL Server 2008 or the free SQL Server Express edition from here

Once you installed, it would prompt you with a login dialog with server details etc., (if you have used it already, you would be familiar with it).  Now, the trick is, to be able to use SSMO with SQL Azure, you need to dismiss the initial login screen and click on “New Query” icon in the top left and specify the server name which is typically like <YOURSERVERNAME>.ctp.database.windows.net (you can find the server name in the screens explained above).  Then specify the username, password and click on “Options” to specify the database that you created above.  Click “Connect” and you should be able to connect to the SQL Azure Server database.  A more detailed step by step instruction is available at Ramaprasanna’s Blog

If you had created the sample database by following the MSDN Sample documentation you can specify that database while connecting (explained in the step above) and then query the tables (select * from T1) to get the results.

Migrating Northwind to the SQL Azure Server

Like mentioned earlier, currently, you cannot take the DB script of say Northwind and run it in the SSMO to be able to create the database in SQL Azure.  There are a few changes required and also few modifications in the script.  Now, doing it for a simple database is quite easy.  However, if you want to migrate a database such as Northwind or Adventure Works, its going to get very complicated and a probable nightmare for you.

Thankfully, there is a SQL Azure Migration Wizard (beta) being developed in CodePlex which is free, open source and under development.  You can view and download it from CodePlex  (Note that it is in Beta and has limited capability in terms of performance, features etc.,)

You can run the SQLAzureMW.exe that gets downloaded once you install the above.  It opens up a screen for connecting to your SQL Server Database

image

Click on “Connect to Server” and specify the servername, credentials etc., and it would list all the databases available in your SQL Server instance.  Click on “Northwind” (this post assumes you already installed the Northwind sample database for SQL Server. If not you can download it from here ) and chose the “Next” step.  It shows the “Script Options” screen where you can change settings.  Clicking on “Next” brings up the screen to chose Object types (SPs, Views, Tables).  I chose, “Script all Object types”

 

image

The next screen provides you to Script it to Window / SQL Azure or to a File.   Chose the “Window / SQL Azure” (default) and click “Next”.  The next screen provides an option to review the configurations made so far.   Click on “Script” and it would parse the scripts and provide the Results Summary.  What this tool essentially does is to make your regular DB Script compatible with a format that is supported in SQL Azure.   Once again since this is in Beta, it may not be near to 100% perfection in this process.

image

The next screen is where you specify your SQL Azure Server Details. Note that the default Server URL that comes is little outdated.  You can get the correct URL from the SQL Azure Portal page (explained in screen shot 2 above) by clicking on the “Connection Strings” icon in the top of the page.  It provides the Server URL as mentioned earlier <YOURSERVERNAME>.ctp.database.windows.net.  You just need to add tcp.  So the fully qualified URL that you need here would look like tcp:<YOURSERVERNAME>.ctp.database.windows.net.  Also, specify the username and password (the one you chose when creating the SQL Azure Database in the first step) and then click on “Test Connection” to check the details.  If you receive an error it might just be wrongly specified server name or missing parts of the URL.   Once you succeed, you can see that it also lists the existing databases (if you haven’t created anything, only “master” would be listed here) and provides the option to create a new database.  You can chose the “Northwind” if you already created it in the SQL Azure portal or type “Northwind” to create it newly.    

image

Next, you can click on “Script” and it does a migration of the scripts to SQL Azure Portal.  It lists down the results in the final screen.

image

Note that this has just migrated the Schema and not the actual Data.  But to take up an on-premise database, generate the scripts and deploy it on SQL Azure manually would be next to impossible, particularly if you have a large database with complex schema.  This tool would help to a great extent in automating the process. 

Finally, we need to upload the Data.  Lets examine it in the next post.

Cheers !!!

.NET 3.5 SP1 now available as a Windows Feature in Windows 7 RTM

Recently I upgraded to Windows 7 RTM and started setting up my machine.   The usual set of tools I install are Visual Studio 2008, SQL Server 2008, Expression etc.,  Also, for .NET 3.5 and Visual Studio 2008 I would require to install the respective SP1 releases as well since they are mandatory and contain tons of new features as well.

I had done this in the past in Windows Vista, Windows 7 RC etc., and while I was trying to install .NET 3.5 SP1 on the new Windows 7 RTM, it surprisingly, popped up a message as below:-

image

I then realized that .NET 3.5 SP1 is now available in Windows Features under “Control Panel – Programs – Turn Windows Features on or off”.  All I had to do, was enable it.

Cheers !!!

 

WebsiteSpark – Helping your small web development companies

You must have heard the buzz around the WebsiteSpark program that we are launching today.  It is a great program that covers a lot of concerns start-ups have – where is the money for me to buy all the software.   Earlier, we had launched programs such as BizPark for the start up eco-system, DreamSpark for students which has helped millions of people world wide.  Today, we are launching WebsiteSpark program targeted specifically at small web companies who develop and design websites.

You can read more about the terms, what you get for free etc., from this great post by Scott Guthrie

I think this is the best time to be an entrepreneur and if we could help you in a little way, we are happy to do that.

Cheers !!!

Download IE8 for Windows XP and get clarified on common myths

IE is by far the largest used browser.   However, one of the common myths around IE is the security, performance and that it doesn't support latest web standards.  Many of the other browsers have openly mentioned in the past that using IE6 is so 2006 days, download blah blah etc., advertising for their browser and thereby conveniently hiding the subsequent IE releases.   It strange how people still compare IE6 after which there are 2 releases with all the modern browsers of today.

The reality of the fact is that after IE6 there have been 2 releases on IE.  The IE 7 and now the latest IE8.  IE 8 is by far the best browser in terms of standards and compliance.  Many web developers out there don't realize that IE provides great help for web development and enhances the web experience to a great extent.

One of the common patterns, we see is that people use Windows XP and have IE6 that came along with it.  Post that the other browsers such as Firefox started picking up momentum and people started using that.  In that process, they didn’t actually realize that IE also released IE 7 for Windows XP (which shipped as the default IE version with Windows Vista) and now IE 8 that can be installed on XP, Vista and Windows 7.

You can watch the IE 8 Video features at http://www.microsoft.com/windows/internet-explorer/videos.aspx?mname=howto_compatibility

Also, for developers and IT Professions, we did a few screen casts that can be viewed at http://www.microsoft.com/india/webcasts/ondemand.aspx 

The best feature I like as a web developer in IE is the Developer Toolbar that helps me accomplish tons of testing.  F12 is your key if you are a web developer and it gives you various techniques for enhancing your web development experience.

In the past, I have also written about how, the IE8’s tab control and process work and session sharing information at http://geekswithblogs.net/ranganh/category/9470.aspx

If you are running IE6 on Windows XP, I would recommend to upgrade to the latest version of IE8 and enjoy the benefits.  You can download it from http://www.microsoft.com/downloads/details.aspx?displaylang=en&familyid=341c2ad5-8c3d-4347-8c03-08cdecd8852b

For Windows Vista, you can install it from http://www.microsoft.com/windows/internet-explorer/default.aspx

If you are running Windows 7 Beta, RC or the RTM version, then you don't have to do anything since IE8 ships as default with it.

And for the statisticians, here is a report on IE’s protection against malware http://nsslabs.com/test-reports/NSS%20Labs%20Browser%20Security%20-%20Socially%20Engineered%20Malware%20Q3%202009.pdf

The excerpt from the above report, is here below

Internet Explorer 8 caught 81% of the live threats, an exceptional score which surpassed the next best browser (Firefox 3) by a 54% margin. Windows Internet Explorer 8 improved 12% between Q1 and Q2 tests, evidence of concerted efforts Microsoft is making in the SmartScreen technology.


Firefox 3 caught 27% of live threats, far fewer than Internet Explorer 8. It was, however, the best among products utilizing the Google SafeBrowsing API. (Note: Firefox 3.5 was not stable enough to be tested during the course of this test. A patch has subsequently become available to address the stability issue. We were able to manually verify that the protection was identical between versions 3.0.11 and 3.5).


Safari 4 caught 21% of live threats. Overall protection varied greatly, with two short periods of severe dips.


Chrome 2 caught just 7% of live threats an 8% drop from the previous test.


Opera 10 Beta caught a mere 1% of live threats, providing virtually no protection against socially engineered malware. In our test bed validation, we verified there was effectively no difference between Opera 9 and Opera 10 Beta.

Happy Browsing !!!

Install Zune 4.0, its free, great for playing music, videos (best you dont need to own a Zune for this)

Yes, few know that Zune software is free for download, can play music/videos from your system with super clarity all with or without you owning a Zune !!!

Its just amazing experience for me, as to the clarity when I play the same song using Zune as against any other software (which includes windows media player, real player etc.,)  Clearly Zune is ahead of its times in terms of the clarity, mixing et all.

While having a Zune can help you take this music with you wherever you go, its super cool even just to have this software installed on your system, just as a music player.

As Microsoft employees, we don't get Zune for free as many would imagine.  I bought a Zune for my wife long back and she has been very happy with it so far.  Its tough to convince people over things that they make up their mind with.  But with Zune, it was simpler for me.  Also, I am waiting for Zune HD to come out.  It is something I would look forward to buy as soon as it is available.

To download Zune software, visit http://www.zune.net/en-us/products/software/download/default.htm

Cheers !!!

What’s new in ASP.NET 4.0 – Part III – Persisting Row Selection in GridView / ListView

Windows Mobile Device Center – Deleted Contacts

If you are using Windows Vista or above and also Windows Mobile Pocket PC or Smart Phone, you would have definitely stumbled upon Windows Mobile Device Center.  It is a one stop place for synchronizing your phone data with your PC i.e. Contacts, Tasks, Emails, Calendar etc.,

Today, while I was setting up my new phone, I accidentally deleted the SIM contacts and worst, synchronized it with my PC using the WMDC and gosh, all the contacts from my Outlook got removed as well.  It was frustrating and kept me nervous over the next few minutes.  Then, I did a bi tof research and finally looked into the “Deleted Items” folder in the Outlook.  There all my contacts were there.  I quickly moved them back to the Contacts folder and also saved my years of contacts.

Well, this post is to help you find it like me, if you happen to end up in a situation like me, so if it helps, it solved the purpose.

Cheers !!!

What’s new in ASP.NET 4.0 – Part II – Routing in Webforms

When I wrote the first post in this series, there was tremendous amount of interest generated and also a lot of feedback requesting to post some of the advanced features.  Like I said earlier, ASP.NET 4.0 has lots of new features some of them as simple as Page.Title whereas so as big as caching improvements.  This post covers one such feature which is Routing in Webforms.  Although Routing was available even in .NET 3.5 SP1, (check this excellent post by Phil Haack on implementing Routing in ASP.NET 3.5 with .NET 3.5 SP1), it was kind of less known.  Also the plumbing work was too much for getting it implemented.

However, this has been much simplified in ASP.NET 4.0.  To give a background, System.Web.Routing is the namespace that provides the all important RouteTable & PageRouteHandler class.  Initially System.Web.Routing was an integral part of ASP.NET MVC.  However, the team must have anticipated that Routing is more important even for Webforms and hence they moved this DLL outside the scope of just MVC and made it available to Webforms as well. 

Importance of Routing:  Getting friendlier URLs which help in better search engine optimization and indexing.  Cleaner URLs that can be bookmarked than the unfriendly querystring based approach.  As more and more URLs are available, the chances of improvement in search engine ranking becomes higher.  These are some of the general advantages of Routing and friendly URLs. 

Ok, now that the context is established, lets start with our sample.  To begin with, I am using Visual Studio 2010 Beta 1 (download link) and Northwind Sample Database (download link)

I created a “File – New Project – ASP.NET Web Application” leaving the default .NET 4.0 as the framework option. Then, I created a bunch of pages i.e Products.aspx, Categories.aspx and also the Global.asax (Add – New Item – Global Application Class)

On the Default.aspx page, I added a GridView and configured it to use the Northwind Database Connection String and the Categories Table therein.  I modified the auto-generated bound columns with a Template Column to accomodate our link to Categories Page.  The modified GridView code looks as below:-

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
            AllowSorting="True" AutoGenerateColumns="False" CellPadding="4"
            DataKeyNames="CategoryID" DataSourceID="SqlDataSource1" ForeColor="#333333"
            GridLines="None">
            <AlternatingRowStyle BackColor="White" />
            <Columns>
               <asp:TemplateField HeaderText="CategoryName" SortExpression="CategoryName">
                    <ItemTemplate>
                   
    <a href="Categories/<%# Eval("CategoryName") %>"><asp:Label ID="Label1" runat="server" Text='<%# Bind("CategoryName") %>'></asp:Label></a>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Description" HeaderText="Description"
                    SortExpression="Description" />
            </Columns>
            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
        </asp:GridView>

As you can see, the Item Template for Category Name is modified to sport a hyperlink to “Categories” page followed by the CategoryName itself.  This would mean that the URL for a category, say Beverages would point to Categories/Beverages

Similarly, on the Categories page, I added a GridView and configured it to use the “Allphabetical List of Products” Table.  I also modified the Bound field for ProductName to a template column to have a link to another Products Page.  The modified GridView code looks as below:-

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
           AllowSorting="True" AutoGenerateColumns="False" CellPadding="4"
           DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
           <AlternatingRowStyle BackColor="White" />
           <Columns>
               <asp:TemplateField HeaderText="CategoryName" SortExpression="CategoryName">
                   <ItemTemplate>
                     
<a href="Products/<%# Eval("ProductName") %>"><asp:Label ID="Label1" runat="server" Text='<%# Bind("ProductName") %>'></asp:Label></a>
                   </ItemTemplate>
               </asp:TemplateField>
               <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit"
                   SortExpression="QuantityPerUnit" />
               <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice"
                   SortExpression="UnitPrice" />
               <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock"
                   SortExpression="UnitsInStock" />
               <asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder"
                   SortExpression="UnitsOnOrder" />
               <asp:BoundField DataField="ReorderLevel" HeaderText="ReorderLevel"
                   SortExpression="ReorderLevel" />
               <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued"
                   SortExpression="Discontinued" />
           </Columns>
           <EditRowStyle BackColor="#2461BF" />
           <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
           <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
           <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
           <RowStyle BackColor="#EFF3FB" />
           <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
       </asp:GridView>

Note, while configuring above GridView, in the screen where we configure DataSource, I also added a where condition to accomodate the Route Request.  The screen looks as below:-

confscreen1

confscreen2

Note that I had selected the Where condition from the first screen and specified “CategoryName” under Column,“=” under Operator and “Route” under Source.  Also specified are the RouteKey “catname” and DefaultValue “Beverages”.  Post this, I just had to click on “Add” and then “Ok” to get a conditional select statement in the SQL DataSource (note: for the purpose of this demo, I have used SQL DataSource.  But this would work even if you used any other datasource type / written ADO.NET Code).  The “Route” type is new feature added under Source in Visual Studio 2010.

Once the above configuration is done, the SQL DataSource code looks as below:-

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
           ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
           SelectCommand="SELECT [ProductName], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [UnitsOnOrder], [ReorderLevel], [Discontinued] FROM [Alphabetical list of products] WHERE ([CategoryName] LIKE '%' + @CategoryName + '%')">
          
<SelectParameters>
               <asp:RouteParameter DefaultValue="Beverages" Name="CategoryName"
                   RouteKey="catname" Type="String" />
           </SelectParameters>
       </asp:SqlDataSource>

I have also added a label to the page just to show the term used to filter and the value for that can be picked up from the Page.RouteData values in the codebehind as follows:-

protected void Page_Load(object sender, EventArgs e)
       {
           if (Page.RouteData.Values["catname"] != null)
           {
               lblDisplay.Text += "<b>" + Page.RouteData.Values["catname"].ToString() + "</b>";
           }
           else
           {
               lblDisplay.Visible = false;
           }
       }

Before getting into Route Configuration, I also added a DetailsView control in the Products.aspx page to show the complete details of a product.   And when configuring the DataSource for the DetailsView, I again specified the WHERE condition to the picked up from the RouteData that would come from the above GridView in Catagories Page.

Once this is done, all that is pending is to configure the Route Values.  In .NET 3.5 SP1 if you want to establish routing, you would have to manually create the WebFormRouteHandler Class and make sure all the pages inherit from this class.  However, in .NET 4.0, it has been much simplied.  All I had to do was open the Global.asax and add the following

protected void Application_Start(object sender, EventArgs e)
        {
             RouteTable.Routes.Add("ProductRoute", new Route("Categories/Products/{productname}",
       new PageRouteHandler("~/Products.aspx")));

            RouteTable.Routes.Add("CategoryRoute", new Route("Categories/{catname}",
       new PageRouteHandler("~/Categories.aspx")));
        }

(note you would need to add System.Web.Routing namespace to be able to use PageRouteHandler, RouteTable classes etc.,)

So, in the Default.aspx page, all the Catagories would have a link that points to /Categories/<CategoryName> and in the Categories.aspx page, all the ProductNames would have a link that points to /Categories/Products/<ProductName>

A typical URL is http://localhost/Categories/Condiments and http://localhost/Categories/Products/Aniseed%20Syrup

Note that similarly, we have close to 10 URLs for Beverages and around 80 URLs (a URL for each product as above) for Products in this particular application.

You can download the sample from  (Add your connectionstring to Northwind Database in the web.config file)

Cheers !!!

What’s new in ASP.NET 4.0 - Part I - View State & SEO Improvements

UPDATE dated August 17, 2009

Once I posted this entry, there is a lot of interest that has been shown and few queries as well.  So I thought I need to update this post.

This is only the first post in the series on ASP.NET 4.0 fetaures.  There are lot of ground breaking things and other enhancements that are pretty exciting.

To the folks who asked for "why MS changing dev platform once in 18 months"

There is no change.  there are a few enhancements.  Post .NET 2.0 there have been a lot of additional APIs such as LINQ, Entity Framework etc., which are different ways of data handling.  While core ADO.NET is still valid, these are additional enhancements that can be used at the Developer's / Architect's discretion. 

For the folks you asked about URL Rewriting

There is URL Routing which is much better than URL Rewriting.  We have talked about it, enough in the past .  You can read more about it at http://www.mostlylucid.net/archive/2009/01/25/asp.net-4.0-webform-routing-quick-rsquon-dirty-version.aspx

I will be covering more features in the following post.

Thanks for the inerest

With Visual Studio 2010 Beta 1 and .NET Framework Beta 1 out for some time, this post is due from me for a long time.   ASP.NET 4.0 has many improvements for different set of scenarios such as Webforms, Dynamic Data & AJAX based web development.  There are also a lot of enhancements to the core runtime that powers ASP.NET such as Caching, Session & Request/Response objects.

For this post, we will examine some of the web form enhancements.  There are sure a lot of them and we will examine some of them in the future posts.

Controlling View State using the ViewStateMode Property – Performance Enhancement

One of the most complained thing in ASP.NET Webform is the growing viewstate which becomes a concern for performance.  While earlier you can set the EnableViewState property to true or false, post that, all the controls, by default inherit and even if you set it to enabled at control level, the behaviour was inconsistent.

With ASP.NET 4.0, the ViewStateMode property helps to determine for every control, whether the ViewState should be enabled, disabled or inherited accordingly.  Ex.-

<asp:Panel ID="pnlViewState" runat="server" ViewStateMode="Disabled">
      Disabled: <asp:Label ID="label1" runat="server"  Text="Value set in markup" ViewStateMode="Inherit"  /><br />
           Enabled: <asp:Label ID="label2"  runat="server" Text="Value set in markup" ViewStateMode="Enabled" />
  <hr />
  <asp:button ID="Button1" runat="server"  Text="Postback" />
    </asp:Panel>

In the code-behind

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            label1.Text = "Value set in code behind";
            label2.Text = "Value set in code behind";
        }
    }

When you run the above page, you can find that the intial value for both the labels is set to “Value set in code behind” whereas after clicking on the button (postback), the value of label1 changes to “Value set in markup” whereas the value of label2 remains unchanged.  As you can see, the Panel which holds both these lables has ViewStateMode set to Disabled and label1 is inherting the mode (this is the default if not specified) and label2 has it enabled.  That is the reason label2 maintains viewstate while label1 loses it.

While it is arguably possible using the simple EnableViewState property earlier, it was never consistent.  Considering the fact that in most of our performance sessions, we talk about disabling viewstate and then enabling it at control level while it doesnt work, this ViewStateMode is a welcome architectural change to improve performance.

Page Meta Keyword & Description – Search Engine Optimization feature

Upto Visual Studio 2008, one can set the Title of the page declaratively or through program using Page.Title.  However, as more and more web traffic is happening through search engines, Page’s Title, Keyword and description become more important.  Although the Keyword feature was exploited and hence many search engines today ignore it, Page Description is something still major search engines such as Google, Bing use for identifying and indexing pages based on content.

The new feature in ASP.NET 4.0 allows users to programmatically set the Page Description and Keywords as follows:-

protected void Page_Load(object sender, EventArgs e)
    {
        this.Page.Title = "My ASP.NET Blog";
        this.Page.MetaKeywords = "ASP.NET, Web Development, Blog, ASP.NET Blog";
        this.Page.MetaDescription = "This Blog contains posts related to ASP.NET and Web Development";
    }

The above code appends the following markup

<meta name="keywords" content="ASP.NET, Web Development, Blog, ASP.NET Blog" />

<meta name="description" content="This Blog contains posts related to ASP.NET and Web Development" />

And the way it works is that, if the meta tags are already present in the HTML markup, whatever is set in the code behind  will fill up the “content” part alone if the “name” tag is matching.

Although this looks simple, it is very useful in cases where you want to set these dynamically based on a condition / criteria.  So far, these were set statically in the HTML.  Now with Page Class level access, these can be set dynamically.

There are many more enhancements to Webforms such as Routing improvements, setting ClientID etc., which we will examine in the future posts.

Cheers !!!

ASP.NET 4.0 QueryExtender, AutoCompleteExtender and UpdatePanel – mashing it up all

(this is a repost since the initial post had a few issues that couldn’t be corrected)

I am playing with the ASP.NET 4.0 QueryExtender released as a part of the Visual Studio 2010 Beta 1.   It provides endless opportunities for working with data without writing much code and when you combine it with a few Ajax features, gives a truly great user experience with very less effort. 

To begin with you need the Visual Studio 2010 Beta 1 and .NET Framework 4.0 Beta 1.  You can install both from http://msdn.microsoft.com/hi-in/netframework/dd819232(en-us).aspx

Also, I am using the Northwind sample database and this can be downloaded from http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46A0-8DA2-EEBC53A68034&displaylang=en

To make things more fun, I am also using AJAX Control Toolkit.  You can download the same from http://ajaxcontroltoolkit.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=27326 You can download just the DLL from the AJAXControlToolkit-Framework3.5SP1-DllOnly.zip link in this page since in this sample, we are just going to use the control.  However, if you already have the AjaxControlToolkit installed, you can simply reference the AjaxControlToolkit.dll file in the Website.

Note that, due to a security implementation in VS 2010, the AjaxControlToolkit DLL cannot be used as is in the projects in VS 2010.  Check this post on using AjaxControlToolkit with VS 2010 Beta 1 http://blogs.msdn.com/webdevtools/archive/2009/05/26/using-microsoft-ajax-control-toolkit-with-visual-studio-10-beta-1.aspx

Once you are done with the installation and other steps, create a new ASP.NET Website.  Note that, for the QueryExtender to work well, you need to make a small web.config update.  You can find the details about this, in my previous post  here  This is just a Beta behaviour.

In the ASP.NET Website, first we will create a LINQ to SQL Class (Right Click Website – Add new item – LINQ TO SQL Class.  Provide this the name “Northwind”.  It would create a Northwind.dbml file, a class file as well as layout file.   Using the server explorer link, connect to the Northwind Database.  For this sample, I am using the Products table.   So, select the table from Northwind database folder under “Tables” and drag and drop it into the LINQ to SQL designer view.  Build the solution.

Once this is done, open the Default.aspx page and add the following code after the form tag.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>

We are adding the above since we are going to use Ajax Futures.  Normally this is not required to use the QueryExtender

Then, add a LINQ Data Source and configure it to use the Products table in the Northwind DataContext created.  The code should look something like below:-

<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="NorthwindDataContext"
            TableName="Products">
        </asp:LinqDataSource>

Post this, I am adding a TextBox, Button and QueryExtender as follows:-

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

<asp:Button ID="Button1" Text="Submit" runat="server" />

<asp:QueryExtender ID="QueryExtender1" runat="server" TargetControlID="LinqDataSource1">
          <asp:SearchExpression DataFields="ProductName" SearchType="StartsWith">
            <asp:ControlParameter ControlID="TextBox1" />
          </asp:SearchExpression>
        </asp:QueryExtender>

Note that the ControlID for QueryExtender’s ControlParameter is TextBox1 and the TargetControlID is LinqDataSource1.  Update these if you gave different ID Names.

Post this, add a GridView to the page and configure it to use the LINQ DataSource created above.  I am not posting the code below since it would make this post too big. 

If everything works fine, you should be able to see a GridView populated with the Products Data and a TextBox and Button when you run the page.

When you type a particular Product Name, say “Anideed Syrup” and click on “Submit” Button, it would filter and show only that particular record in the GridView.  Note that, you haven’t written any code for this filtering so far.  All happens by virtue of the QueryExtender control.  We have used SearchExpression in this case and it has stuff like StartsWith, EndsWith, contains for SearchType that can be used exhaustively for different requirements.  Also, there is RangeExpression, PropertyExpression etc., 

The input for the QueryExtender can also come from various sources.  In this case, it is TextBox and hence ControlParameter.  You can also use QueryString, Cookie, Form, Profile, Session etc.,

For a more exhaustive sample on QueryExtender, check http://msdn.microsoft.com/en-us/library/dd537669(VS.100).aspx

Now that we have a search behaviour, we would like to go little further and make this whole stuff asynchronous so that the operation is smooth.

Add an UpdatePanel and place all the above inside the ContentTemplate of the UpdatePanel.

When you run the page now and type a search item and click on the “Submit” button, the results bind asynchronously without a postback, making it look better.

One final touch is to provide search suggestions.  For this, I would be using the AutoCompleteExtender feature.  If you already have the AjaxControlToolkit installed, you may want to remove it from ToolBox and do the step in paragraph 5 (security implementation in VS 2010)  above and then add it to the Toolbox again. 

Drag and drop the AutoCompleteExtender into the page and set its TargetControlID to TextBox1. 

Now, the AutoCompleteExtender requires a Web Method to retrieve the values asynchronously.   We will use PageMethods for this so that we avoid creating a separate webservice.   For this purpose, we will use the same DataContext created by the LINQ DataSource Control above.

Swtich to the code behind of the Default.aspx page i.e. Default.aspx.cs file and add the following using statements

using System.Web.Services;
using System.Configuration;

Post that, the method for retrieving product name is as below:-

[WebMethod]
    public static IQueryable GetProductNames(string prefixText)
    {
        NorthwindDataContext nwdc = new NorthwindDataContext();

        var productList = from Product in nwdc.Products
                          where Product.ProductName.StartsWith(prefixText)
                          select Product.ProductName;

        return productList;
     }

With this, we are getting a list of Products whose names start with the prefixText.  The prefixText is the one used in the AutoCompleteExtender and length can be set using MinimumPrefixLength from 1 to 2,3 etc.,  This is basically the number of characters you need to type before the suggestions need to show up.  Then configure the ServiceMethod for the AutoCompleteExtender to GetProductNames (the method above).  The updated AutoCompleteExtender code should look like

<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
                    MinimumPrefixLength="1" TargetControlID="TextBox1" ServiceMethod="GetProductNames">
                </cc1:AutoCompleteExtender>

Once you have all of these, run the page and when you start typing the ProductName in the TextBox, it should start showing suggestions.  Select one of them and click on the “Submit” Button and you should get the result bound to GridView, all happening without a postback.

You can improve the layout with better CSS for the AutoCompleteExtender, better layout for GridView, Button etc., to further improve the experience.  I have posted a few sample screen shots below and also attached the source code for the above sample with this.  Note that there are far too many steps involved in setting up the website rather than the actual code work, so if something doesn’t work, make sure you have checked all the initial steps mentioned by me in the beginning.  Hope you find this sample useful.

Download the sample from http://cid-069f94a102eff49a.skydrive.live.com/browse.aspx/QueryExtenderSample

screenshot1

screenshot

Cheers !!!

Virtual TechDays – the team

«November»
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345