SQL SERVER – Corrupted Backup File and Unsuccessful Restore

October 26, 2010 § Leave a comment

SQL SERVER – Corrupted Backup File and Unsuccessful Restore

by pinaldave

If you are an SQL Server Consultant, there is never a single dull moment in your life. Quite often you are called in for fixing something, but then you always end up fixing something else!

I was recently working on an offshore project where I was called in to tune high transaction OLTP server. During work, I demanded that I should have a server which is very similar to live database so I could inspect all the settings and data. I may end up running a few queries which may or may not change the server settings. The Sr. DBA agreed and instructed the Jr. DBA accordingly to restore a database from their backup.

In a few minutes, their Jr. DBA arrived running to us, asking for our help. The problem was that when he attempted to restore the database, he was not able to restore the database as their backup. This eventually threw an error. Now this was very alarming for them because their backup file had some issues. I suggested trying some backups but again, the same issue occurred on all of them.

The CTO, who was also present at the location, got very upset with this situation. He then asked when the last successful restore test was done. As expected, the answer was NEVER. There were no successful restore tests done before.

During that time, I was present and I could clearly see the stress, confusion, carelessness and anger around me. I did not appreciate the feeling and I was pretty sure that no one in there wanted the atmosphere like me.

The next step was to take a backup of their database right away. The CTO wanted to observe the complete process so he could figure out where the error originated and where was its exact location.

Here is the error they were receiving when they attempted to restore the database:

Msg 3243, Level 16, State 1, Line 1
The media family on device ‘D:\TestDB.bak’ was created using Microsoft Tape Format version 1.22. SQL Server supports version 1.0.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.

The first thing I attempted to do is to take a backup of the database on another spare drive by myself. After having that backup, I tried to restore it to the database. As what I expected, it was successfully restored. Now that event provided me the information that there was nothing wrong with how the backup was done. The problem was located somewhere else. I asked them about their current process of taking a backup and storing it. They provided me the following diagram:

Looking at the diagram, I decided to test their FTP software. I uploaded  our organization’s FTP space. After it was done, I restored the database again and it worked without an error. This led me to think that there is something wrong in their UNIX server. After talking to their UNIX administrator, he informed me that they were running some cron jobs to compress the files and they were also moving those files to a larger drive. After listening to this, I was very sure there was something wrong during that process which had something to do with the .bak file because it was not able to work properlu.

After a few tests, the UNIX administrator accepted that that cron job was changing the structure of the file. In the meantime, he disabled the process to avoid this corruption. The CTO then asked me if there was any way they could tell if the backup which was already taken was good as gold or if there was a corruption in it.

Here is the command that you can run on your database file so you can check if the database file is intact or if it has any corruption in it:

FROM DISK=N'D:\TestDB.bak'

The question is, “Do you practice this on your production server’s backup?”



The reason i posted this in my blog…seriously there are lot of issues when it comes to recover the database…

I had faced earlier.. we need to back up every now and then..Hope this is useful



7 Ways Windows Phone 7 Is Cooler Than The iPhone

October 22, 2010 § Leave a comment

People Come First

Some commenters have been confused by Microsoft’s first batch of Windows Phone 7 ads, which make the pitch that you should be spending less time with your phone. Isn’t loving your phone a good thing?

People Come First

Yes, but Microsoft’s making a point about Phone 7’s design, which lets you do more stuff without constantly navigating between apps. The best example is the People hub, shown here. This looks like a normal contact list, like the iPhone and every other smartphone has. But each contact’s image is automatically updated from their most recent Facebook image. Click on each one, and you get a wealth of options: you can make a call, send an e-mail or text, post on their wall, view pictures they’ve recently posted, and so on. Everything you want to do is based around that person, not locked up in different apps.

Facebook is Built In

Facebook is Built In

Microsoft’s partnership with Facebook pays off in a huge way with Windows Phone 7. There’s no Facebook app to download–it’s built into the phone already. All you have to do is log on with your Facebook account information, and all your Facebook contacts and pictures will be imported into your phone. This is an example of what my Start screen would look like, with my pictures and my family showing up the instant I activate the phone. This demo page gives you an idea what yours might look like.

The Camera Makes More Sense

The Camera Makes More Sense

Every Phone 7 will have a 5 megapixel camera or better, but once again, the hardware isn’t the interesting part. When designing the camera UI, Microsoft specifically targeted one of the most annoying things about the iPhone: when you take a photo, you have to switch over to the photo roll view to see if the shot was any good, then switch back to the live camera to take another picture. With Phone 7, the live viewfinder is integrated right next to all your old shots. So here, that image on the left is an old photo. The image on the right is the live shot I’m taking right now, of a coffee cup on the conference room table.

Documents, Spreadsheets, and Slides, Oh My!

Documents, Spreadsheets, and Slides, Oh My! It isn’t sexy, but sometimes it would be convenient to be able to get at Word documents, PowerPoint slide shows, and Excel spreadsheets on your phone.  (This is a particularly fancy spreadsheet with a chart embedded.) Phone 7 lets you view and edit Office files both on the phone and stored on a corporate SharePoint server, and there are some useful tricks like an Outline mode that lets you quickly jump to headers in a long document.

Xbox Live

Xbox Live Xbox Live is like a social network for hardcore gamers. While the rest of us might not care, a lot of its approximately 20 million users are devoted to the service. Windows Phone 7 is the only phone that will let Xbox Live gamers use their identities and play turn-based games against their friends.

Unlimited Music

Unlimited Music

or big music fans, the Zune Pass is the best subscription deal around: $15 per month gets you an unlimited number of streams or temporary downloads (that is, downloads that stop working when you stop paying your subscription), plus 10 MP3 downloads you can keep forever and transfer to an unlimited number of devices. It basically turns the millions of songs Microsoft has licensed for the Zune Marketplace into your personal library.

The only problem was that the Zune Pass was available only on the Zune music players, which nobody bought, and which had only a Wi-Fi connection. Now it’s going to be available with Windows Phone 7 in the U.S. and most European countries. And unlimited music over a 3G connection is a lot more appealing than having to find a Wi-Fi hotspot.

Falling Through the Clouds

Falling Through the Clouds

The maps experience on Phone 7 is nothing short of amazing. When you first pick a location, it shows it on a normal grid-like map. As you zoom in, the grid gradually changes to a satellite view. Portions of the image that aren’t filled in yet appear grey, as if you’re descending through clouds. It’s one of those things that sounds trivial, but feels and looks right when you try it in person.

And that’s the biggest challenge Microsoft faces with Phone 7: you have to use it to be impressed by it. Demos and photos don’t do it justice. Apple had hundreds of Apple stores when it launched the iPhone. Microsoft has four Microsoft Stores. It’s relying heavily on AT&T and T-Mobile to provide demonstrations, and even training salespeople in how the phones work. But consumers go to the Apple Store just to browse, and eventually maybe end up buying something they’ve fallen in love with. Nobody visits the AT&T store for fun.

Facebook warns developers after privacy leak

October 22, 2010 § Leave a comment

Facebook issued a stern warning to independent developers Monday in response to reports that some applications on the site were sharing identifying information about users. 

At the same time, a Facebook engineer said media coverage of the leak has exaggerated how much information can be, and has been, shared with third parties.

“Our policy is very clear about protecting user data, ensuring that no one can access private user information without explicit user consent,” Facebook engineer Mike Vernal said on a blog used by people who develop apps for the site. “Further, developers cannot disclose user information to ad networks and data brokers.

“We take strong measures to enforce this policy, including suspending and disabling applications that violate it.”

A report by The Wall Street Journal found that some of Facebook’s most popular apps, including the game FarmVille by social network game company Zynga, were being used to share users’ personal information with more than 25 advertisers and online tracking companies.

According to the Journal, the apps were sharing the unique “Facebook ID” numbers that are assigned to every user on the site and can be used to look up a person’s name — even if that person has set all of his or her Facebook information to be private.


A Check and Foreign Key Constraint Improves Query Performance

October 22, 2010 § Leave a comment

The optimizer uses foreign key constrains and check constraints to create more efficient query plan by skipping some part of the query plan because the optimizer can see that there is a foreign key constraint so it is not necessary to execute that part of the plan. Let’s prove this with the help of an example. Consider the two tables below.

Create Table sales
                CustomerID INT Primary key

Create Table SalesOrderdetail
                SalesOrderID int Primary key,
                CustomerID int Not Null
                        Constraint FTCustomerID
                                References sales (CustomerID)

Insert Some values in the tables.

insert into sales (CustomerID)
values (1)

insert into SalesOrderdetail(SalesOrderID,CustomerID)
values (1,1),(2,1),(3,1),(4,2),(5,2),(6,2),(7,3),(8,3),(9,3),(10,4),(11,4),(12,4),(13,5),(14,5),(15,5)

Let’s look at what SQL Server does when there’s a foreign key. Consider the following select query. Please include the actual execution plan by pressing Cntrl-M, or from the Query Menu, choose include actual execution plan.

select so.* from SalesOrderdetail as so
where exists (select * from sales as s
 where so.CustomerID=s.CustomerID)

If you see the execution plan below after you’ve run the above select statement, you will see that the optimizer doesn’t even look at the sales table. Only salesorderdetail table is accessed. This is because the optimizer knows that it is no point executing the EXISTS operator as the foreign key constrain requires all sales to refer to an existing customer which is what the WHERE clause is doing.


Fig. 1


Now, let’s turn off the foreign key constraint.

Alter Table SalesOrderdetail nocheck constraint FTCustomerID;

Run the same select statement

select so.* from SalesOrderdetail as so
where exists (select * from sales as s
                                where so.CustomerID=s.CustomerID)

The execution plan below shows that the optimizer now executes the EXISTS operator to return only those salesorder rows that have a reference to the customer. Since we switched off the foreign key constraint, the optimizer wasn’t sure whether salesorder had valid customer references. That’s the reason why it had to execute the EXISTS operator. If you have a big table, this can make a big difference as far as performance is concerned.


Fig. 2


Let’s turn on the foreign key again by executing the following statement.

Alter table SalesOrderdetail check constraint FTCustomerID;

Now if you run the same select statement again you will still see the execution plan shown in Fig. 2. Why is this happening? You have switched on the foreign key constraint, and it should now execute the plan in Fig. 1. But it’s not doing that. This is because the foreign key constraint is ‘not trusted’. The optimizer does not take into account a constraint that is not trusted. The foreign key is not trusted because a user might have inserted or updated a sales row with an invalid CustomerID. When you switch it on, it does not verify the previous data by default.

You can check the status of your foreign key constraint by running the following query.

select name,is_not_trusted from sys.foreign_keys where name= 'FTCustomerID'

This will show you that the is_not_trusted column = 1 indicating that your foreign key constraint is not trusted. To make it trusted include the WITH CHECK option in your query as shown below.

Alter table SalesOrderdetail WITH CHECK check constraint FTCustomerID;

This checks that all rows in the table comply with the constraint before turning it on. If any rows do not comply with the constraint then an error message is returned and the Alter Statement is rolled back.

If you check the status of the constraint again, you will see that the is_not_trusted column shows 0. Now, when we run the first select statement we get the first execution plan as shown in Fig. 1.

select so.* from SalesOrderdetail as so
where exists (select * from sales as s
                                where so.CustomerID=s.CustomerID)

Let’s make it a bit more interesting. Let’s change the table structure of the members table such that TeamID column allows NULLs.

drop table SalesOrderdetail
Create Table SalesOrderdetail
                SalesOrderID int Primary key,
                CustomerID int Null
                        Constraint FTCustomerID
                                References sales (CustomerID)

Now if you run the same query against this new table structure, you will get execution plan shown in Fig. 2. This means that the optimizer is executing the EXISTS operator even if the foreign key constraint is trusted. To get back to the first execution plan (Fig. 1), which did not execute the EXISTS operator you will need to change the query as shown below.

select so.* from SalesOrderdetail as so
where exists (select * from sales as s
                                where so.CustomerID=s.CustomerID)
and so.customerID is not null   

This informs the SQL server that no member with TeamID of NULL should be returned. This again brings you back to the first execution plan (Fig. 1) where it doesn’t execute the EXISTS operator.


In this article I have showed that check and foreign constraints do not degrade performance but actually improves performance.


Source : sqlservercentral.com


Windows Tablet 7 Coming, but When?

October 22, 2010 § Leave a comment

Prediction: Microsoft will ship a tablet OS based on the Windows Phone 7 platform.This belief is not based on statements by Microsoft, inside information or even wishful thinking. It’s based on what Microsoft has done in the past.

Here’s the standard Microsoft pattern:

1) Some innovative competitor launches a new platform.

2) Microsoft takes a wait-and-see approach rather than jumping in.

3) After years of Microsoft doing nothing, the competitive platform grows a new market too big to fail.

4) Microsoft then launches a huge initiative resulting in a more powerful, feature-rich and backward-compatible alternative (which is also far more expensive and bloated).

5) Microsoft tries to outspend its competitor with marketing and promotions.

6) Once it is clear that Microsoft’s approach has been rejected by the market, Microsoft comes around and relaunches a new approach that’s a lot more like its competitor’s.

7) After a few version tweaks, Microsoft finally ships a great product. Unfortunately, by this time, it’s too little, too late. Even with a great product, Microsoft can’t achieve its original goal of being a dominant player in the market.

This pattern has been followed by Microsoft in music players, search engines, cloud-based office suites, ultra-mobile computers and multi-touch smart phones.

The same pattern is also playing out in the tablet business. But it might not be too late for tablets.

Microsoft’s great-but-too-late multi-touch smartphone, Windows Phone 7, goes on sale today. It’s not clear that Microsoft is even working on a Windows Phone 7-based tablet. All noise from Redmond indicates that Microsoft intends to continue slogging on with expensive, bloated desktop PC-based pen tablets.

If Microsoft’s history is any indication of its future, Microsoft will admit failure and launch a multi-touch tablet based on a cell phone operating system in about two years, which will be too late to make a serious dent in the market now dominated by Apple and very soon to be two horse race between Appleand Google.


How Microsoft Can Succeed In the Tablet Business

Microsoft has an opportunity to occupy a unique position in the coming massive multi-touch tablet market. The key to understanding that position can be found in the current war between Google and Apple over “open” versus “integrated.”In a conference call this week, Apple CEO Steve Jobs slammed Google’s Android platform by saying that, although Google calls their approach “open,” the better word is “fragmented.” Apple’s iOS platform on the other hand, isn’t so much “closed,” as Google characterizes it, but “integrated.”

Jobs’ position is that Android comes with too many user interfaces and on too many handset models. As a result, users themselves must serve as “systems integrators.”

Google hasn’t responded to the jab in any meaningful way. But if they did, they would probably say that the Android approach provides vastly more choice — both for hardware makers and for users — more flexibility and more freedom from the whims and dictates of a single company.

Microsoft’s opportunity is to create a touch-tablet ecosystem that offers the choice, flexibility and freedom of the Android market with the universal compatibility and interface predictability of the iOS market

In fact, jobs even faintly praised Microsoft during the call — or at least contrasted Microsoft favorably against Google — by saying that “on Windows… Most PCs have the same user interface and run the same apps.”

And that’s true. Microsoft has done a better job on Windows with standardizing user interfaces and offering application compatibility than Google has done with Android.

By extending this core competency to a new Windows Phone 7-based tablet operating system, Microsoft could offer users the best of both worlds — a welcome alternative to both Google’s “fragmented” and Apple’s “closed” approaches.

There are other opportunities to differentiate. Microsoft could leverage its dominance in desktop office suites by offering perfectly compatible “lite” versions of Word, Excel, PowerPoint and Outlook (something a little more than what’s in Windows Phone 7, but a lot less than desktop versions, feature-wise).

In fact, Microsoft could probably even get away with pre-installing these applications, given that the “monopoly” argument couldn’t be credibly used against Microsoft in the tablet space.

Such a bold move could immediately establish Microsoft’s multi-touch tablet product as the new business standard.

And finally, the Windows Phone 7 user interface offers something incredibly compelling for tablets not currently available on the iPad: the replacement of icons with user-configurable update boxes. On Windows Phone 7, the main screen shows updated Tweets of friends, stock price changes, sports scores – potentially any data you want.

This feature is of limited value on a phone, which is either in your pocket or being used – you’re not likely to sit there staring at the screen waiting for the information to update. But on a tablet, you could easily imagine doing that.

Just prop up your Windows Tablet 7 device next to your PC, and you’ll have an instant dashboard monitoring everything you care about. Everyone would want that. And nobody else has it.

Microsoft hasn’t got a prayer of competing against Apple in the consumer touch-tablet space. But the company could be a leader in business touch-tablets. Windows Phone 7 is the right approach. The only thing Microsoft needs to do is ship as soon as possible. Not in two years. Not late next year.

The window is closing fast for Microsoft to avoid its habitual error of shipping the wrong product at the right time, followed by the right product at the wrong time.

Microsoft has the right product, more or less. By quickly transforming Windows Phone 7 into a Windows Tablet 7 OS, the company could have the right product. And if the company can do so within six months it would be the right time, too.

Come on, Microsoft. Think different!


Office 365: Microsoft put its Office suite in the cloud

October 20, 2010 § Leave a comment

Microsoft has bowed to the inevitable and announced it is making its Office suite available as a subscription service in the cloud.

The new cloud offering – called Office 365 – launched in beta yesterday, with full worldwide launch in 40 countries planned for next year.

Office 365 will see Microsoft’s productivity suite bundled up with its collaboration, email and unified communications web services SharePoint Online, Exchange Online and Lync Online. Microsoft Dynamics CRM Online will also be added to the offering next year.

Businesses are no longer asking whether they should move to cloud, according to Kurt DelBene, president of Microsoft’s Office Division, speaking at the launch of Office 365, “but when and what to move”.

Microsoft Office 365: Login

Microsoft’s Office 365 productivity suite
(Screenshot: Microsoft)

“We are unequivocally at a pivot point in the adoption of cloud services,” he added.

Microsoft will be offering two flavours of Office 365 – one for SMEs with up to 25 employees, and one for enterprises. The latter will include a sliding price per seat scale to cater for different types of users.

The list price for Office 365 for enterprises starts at $2 per user per month, for a basic service offering email functionality, rising to $27 per month for a fully featured productivity suite suitable for a C-suite exec. Volume discounts can also apply.

“One size does not fit all in this segment,” said Chris Capossela, vice president of Microsoft’s Office Division. “[Office 365 for enterprise offers businesses] a single platform for all their users. You’re not going to use one company’s solution for as certain set of users and another company’s for another. That’s a management nightmare.”

Office 365 for SMEs will cost $6 per user per month – and will allow start-ups, entrepreneurs and SMEs to tap up the same enterprise-grade software as larger competitors, said DelBene. “They can compete with those large organisations immediately – right out of the gate,” he added.

Redmond is also including…

…a 99.9 per cent uptime money-back guarantee for Office 365.

By putting Office in the cloud Microsoft is potentially leading one of its most lucrative cashcows to slaughter. Philip Carnelley, research director at analyst house TechMarketView, said that Office currently generates around $18bn in revenues per year – with the Office business accounted for almost half of Microsoft’s total operating profit last year.

Moving to a software as a service (SaaS) subscription model is necessary for Microsoft to compete with the likes of Google and IBM in the office productivity sector, according to Carnelley, but “will squeeze margins” in Redmond.

Microsoft Office 365: Document sharing

Document sharing via Microsoft’s Office 365 productivity suite
(Screenshot: Microsoft)

“Microsoft can’t afford to lose share but it also looks clear to us that moving to a SaaS solution – with its pay-as-you-go flexibility, the need to provide huge datacentres to support the applications and storage – will squeeze margins. More than that, a SaaS offering which only requires a browser means it’ll become easier than ever to switch providers, which will impact on prices, further lowering margins and revenues,” he said in a statement.

“This was a necessary step but the debates in Redmond must have been fierce,” Carnelley added.

Microsoft’s Capossela claimed Office 365 represents new business opportunities for Microsoft both at the low end – in reaching the IT department-less customers that they’ve never reached before – and also in the enterprise sphere as the company broadens its offering.

“Traditionally Microsoft has only competed in the software space which is about 15 per cent of any IT budget,” said Capossela. “With Office 365 and out other cloud services we’re actually now in much larger pool of IT spend because we’re actually running a company’s infrastructure.”

In addition to Office 365 for SMEs and enterprises, Microsoft said it will launch Office 365 for education next year to target the academic community.



New Features in Microsoft Visual Studio 2010 and the .NET Framework 4.0

October 18, 2010 § 1 Comment

Visual Studio 2008 may be better than sliced bread, but the development team at Microsoft has already been working on the next release. They have recently given us Visual Studio 2010 and the .NET Framework 4.0 as a Community Technology Preview (CTP); it boasts several features that would appeal to developers.

This article won’t go into every single feature, but will go into features that are the most relevant to .NET developers. Please note that because this is a CTP, it doesn’t mean that the final release will be exactly as you see in the CTP or as is described here. I can go over the features roughly as follows:

New Features in the Visual Studio 2010 IDE and .NET Framework 4.0

  • Call Hierarchy of methods
  • A New Quick Search
  • Multi-targeting more accurate
  • Parallel Programming and Debugging
  • XSLT Profiling and Debugging
  • The XSD Designer

New ASP.NET features

  • Static IDs for ASP.NET Controls
  • The Chart control
  • Web.config transformation

New VB.NET features

  • Auto Implemented Properties for VB.NET
  • Collection Initializers
  • Implicit Line Continuations
  • Statements in Lambda Expressions

New C# features

  • Dynamic Types
  • Optional parameters
  • Named and Optional Arguments

Conclusion and Resources

New Features in the Visual Studio 2010 IDE and .NET Framework 4.0

Call Hierarchy of Methods

In complicated solutions, a single method may be used from several different places, and attempting to follow how a particular method is being called can be difficult. Call hierarchy attempts to address this problem by visually presenting the flow of method calls to and from the method you are looking at. In other words, you can look at what calls your method and what your method calls in a treeview format.

Obviously, I cannot present a truly complex example, but a simple example should help illustrate the point.

protected void Page_Load(object sender, EventArgs e)

private void BindDataControls()
   //DataBinding here

protected void Button1_Click(object sender, EventArgs e)

Now, if you wanted to figure out what calls BindDataControls(), you can right-click on it and choose “View Call Hierarchy.”

This gives you a window with a treeview format, as shown below, with nodes that you can expand ad infinitum (or until your machine runs out of memory). You also can right-click on the method names and go to their definition, or you can reset those methods as the root of the Call Hierarchy window if you want to work your way from there and don’t care about other methods anymore Further, you can view call hierarchies from the object browser too, so you needn’t always be viewing the code. This is a helpful visual cue for very complicated projects that we’ve all worked on at some point or another.

(Full Size Image)

A New Quick Search

A nifty little feature that Microsoft has added is the Quick Search window. This isn’t the same as the Search or Search and Replace window that searches for specific textual strings. It’s different in the sense that it searches across symbols (methods, properties, and class names) across your solution and filters them in the result view for you.

In this example, I typed in ‘but’ and it brought back all symbols that contained ‘but’ regardless of position. You can specify multiple words to search for by separating them with a space.

(Full Size Image)

Multi-targeting more accurate

Although VS 2008 supports targeting different frameworks from the same IDE, one problem was that the Toolbox and Intellisense displayed types that were available to the .NET 3.5 Framework whether or not you were working with a .NET 3.5 project. This may have caused problems when you tried to use something, only to realize that it wasn’t actually available to you.

VS 2010 gets smarter by only displaying items that you can use in the Toolbox and Intellisense (and other relevant areas).

Further, if you change your project to use a framework version that isn’t available on your machine, you will be prompted and can choose to retarget to another version or download the target framework that you wanted.

Parallel Programming and Debugging

Don’t let the name intimidate you. I think Microsoft has done a great job of allowing you to take advantage of multi-processor systems with very easy syntax to enable parallel programming that you can quickly adapt to.

In addition, to make things easier, VS 2010 comes with a set of visual tools that will help you debug and view simultaneously running threads. This means that you can view the task instances and the call stacks for each task in parallel.

If you’ve been using the Parallel Extensions to the .NET Framework, then most of this will be familiar to you.

A Task.StartNew will kick off your threads for you. If you then hit a breakpoint and view the VS 2010 Threads window, you can view the state of each thread and where it is currently. This can be seen below—the green indicating the main thread and the yellow indicating all the worker threads spawned.

(Full Size Image)

There will also be a Multistack window that allows you to peruse the call stacks of all of the threads currently being executed; this is again a helpful visual cue that groups together tasks sharing a stack frame.

Parallel Programming itself becomes a feature of the .NET Framework 4.0 as opposed to it being an extension right now. With Parallel Programming, you get Parallel LINQ (PLINQ) and syntax to make parallelization of algorithms easier. In fact, it’s unbelievably easy.

Say you have a for loop that performed a complicated task:

for (int i = 0; i < 10; i++)

Assuming DoSomethingReallyComplicated does something really complicated (as the name implies), you could parallelize it by using Parallel.For and enclosing the iteration in a lambda expression.

Parallel.For(0, 10, i => { DoSomethingReallyComplicated(i); });

Similarly, there is Parallel.ForEach<> for foreach loops. You could also use Parallel LINQ to do the same thing. Taking a theoretical, basic LINQ equivalent to the above, you would get this:

from i in Enumerable.Range(0,9)
   where DoSomethingAndReturnAValue(i)
   select i

PLINQ would involve a very slight change; just add AsParallel():

from i in Enumerable.Range(0,10).AsParallel()
   where DoSomethingAndReturnValue(i)
   select i

You should be able to see the real effects of these changes on multi-core machines under intensive circumstances. Of course, there is much more than I’ve gotten into here, such as parallel profiling views, but that’s beyond the scope here. You could get started now, if you’d like, by downloading the Parallel FX CTP.

XSLT Profiling and Debugging

Everyone hates XSLT. If you don’t hate XSLT, you haven’t used it enough. Part of this attitude towards XSLT stems from the difficulty you face when debugging it—it is a huge unknown and can blow up in your faces when you least expect it.

Visual Studio 2010 will offer an XSLT profiler to help with writing XSLT in the context of profiling and optimization. After writing your XSLT, you can use the “Profile XSLT” option in Visual Studio to supply it with a sample XML file that gets used for the analysis.

I decided to test out a sample XSLT from the Gallery of Stupid XSL and XSLT Tricks page because they would undoubtedly be complicated. The XSLT Profile on Compute square roots using the Babylonian Method produced this:

(Full Size Image)

Clicking on the ‘offending’ functions then takes you to the function details, among other views on the analysis available to you. Available to you are the paths of execution taken, assembly-level view of the execution, call hierarchy, statistics by function, and function details.

(Full Size Image)

Also available to you in the menu options is XSLT Debugging. You can launch an XSLT file with sample XML and step through it as you would normal managed code.

(Full Size Image)

No, your eyes aren’t deceiving you. You can set breakpoints, have locals set, and step through the template functions as you please. This should help alleviate your collective fears of XSLT immensely.

The XSD Designer

While I’m on the subject of XML, VS 2010 also introduces a new XSD Designer.

(Full Size Image)

It comes with a schema explorer, a visual view of the relationships in different levels of detail, and sample XML generation.

New ASP.NET Features

Static IDs for ASP.NET Controls

A few much-needed features make their way to ASP.NET in the .NET Framework 4.0. You now have the ability to specify the ClientID that gets rendered to the page instead of having to fiddle with viewstate or hidden fields to manage the IDs that get generated out to the page. If you’ve ever had to use the .ClientID property of a control or found yourself using ClientScript.RegisterStartupScript or ClientScript.RegisterClientScriptBlock, you will know what I mean; it doesn’t always feel good to have to write all your JavaScript in the codebehind. It’d be nice to let the JavaScript sit on the page or in an external JavaScript file—where it belongs—so that a change in the JavaScript doesn’t require a recompilation of the website, while at the same time still using dynamic ASP.NET controls.

With ASP.NET 4.0, you now can create controls that support static Client IDs. To do this, simply get your control to implement INamingContainer. When using the control on the page, set its ClientIDMode property to Static.

For example, here is the codebehind for a simple web user control (ASCX) with a label in it.

public partial class WebUserControl1 : System.Web.UI.UserControl,
   protected void Page_Load(object sender, EventArgs e)
      this.ClientIDMode = ClientIDMode.Static;

You would need to expose the ClientIDMode property so that the parent page can set it. That’s all you need to do, and the control gets rendered to the page with an ID of Label1.

When it comes to databound controls, though, you’d have to do things a little differently; it’s really not acceptable to have more than one control with the same ID on a page. For this purpose, the ClientIDMode can be set to predictable and you also can specify a suffix that ensures that the IDs generated are predictable (but not fixed).

An example of its usage would be (in a gridview):

<asp:GridView ID="GridViewTest" runat="server"
              ClientIDMode="Predictable" RowClientIDSuffix="Pizza">

And any controls rendered in the gridview should have IDs like “GridView1_PizzaLabelTest_1”.

The Chart Control

The Chart control is finally here! This control sports various chart types, including point, column, bar, area, doughnut, range, and types I hadn’t even heard of before such as Renko and Kagi…. The chart also has scale breaks for ‘excessive’ data, and even can be rendered in a 3D mode. As a quick test, I got to make these charts based on the meteor consumption of my friends:

(Full Size Image)

Combined with ASP.NET AJAX functionality, this can open up a vast array of presentation configurations for your website if you deal with such data.

The chart works off an HTTP Image Handler. This means that you also have the option of plugging in your own charting image handling assembly if you want to customize it further.

Web.config transformation

In enterprise environments, your ASP.NET application will have to go across various stages of deployment such as testing, staging, preproduction, and production. Due to the relatively isolated nature of these environments, you often will have had to create separate web.config files for each environment and ensure that any changes you make to one web.config has made it to the other web.configs as well.

VS Team System 2010 has implemented a web.config transformation feature that can perform the value-based transformation that you need when deploying to different environments. The transformation is performed as part of an MS Build task, but you will need to specify the transforms to perform across the various web.configs; this is done by adding a set of xdt:Transform attributes to various nodes that may need changing (such as the obvious connection string).

An example of this would be:

<add name="theSiteDB"
                       User Id=hello;password=world"
     providerName="System.Data.SqlClient" xdt:Transform="Replace"

Because of the XML-based nature of these transforms, it therefore is also possible to perform the transformation manually via the VS 2010 GUI or create deployment packages for the various environments that require minimal human intervention.

New VB.NET Features

Auto implemented properties

Often, you find yourselves declaring public properties like this:

public string DoorColor
      return doorColorValue;
      doorColorValue = value;

In VB.NET, this would be:

Public Property DoorColor As String
      Return _doorColor
   End Get
   Set(ByVal value As String)
      _doorColor = value
   End Set
End Property

More often than not, no extra logic ever gets placed in the get/set blocks. This is why C# was given an auto implemented property in which the private variable is declared behind the scenes for you.

public string DoorColor
   get; set;

This feature was not present for VB.NET in .NET Framework 3.5, but is now available in .NET Framework 4.0. It’s as simple as this:

Public Property DoorColor As String

Collection Initializers

The syntax to initialize collections in VB.NET 10 (in .NET Framework 4.0) is now slightly shorter.

Dim breakfast = {New Crumpets With {.CrumpetAge = 99,
                                    .CrumpetSmell = "Bad"},
   New Crumpets With {.CrumpetAge = 29, .CrumpetSmell = "Good"}}

Note that you don’t need to specify the collection type because it is implicitly understood. In .NET 3.5, this would not have compiled because it would have understood ‘breakfast’ as type ‘Object’ instead of Crumpets. .NET 4.0 understands Crumpets, a statement I never thought I’d actually write down.

Implicit Line Continuations

C# has had this for a long time—long lines of code can be split across several lines for more readability. VB.NET has had it, but you’ve always had to add an underscore (_) at the end of each line, which could get a little annoying. Certain types of statements can now be split across several lines without the _ required.

Therefore, the collection initializer example from the previous section can be declared like this:

Dim breakfast =
      New Crumpets With {
                    .CrumpetAge = 221,
                    .CrumpetSmell = "Foul"
      New Crumpets With {
                    .CrumpetSmell = "good",
                    .CrumpetAge = 1

It works on Console.WriteLine, too.


And with nested method calls.


Changes to Lambda Expressions: statements and subs

In VB.NET 9 (.NET Framework 3.5), Lambda Expressions always needed to return a value regardless of whether it was required or not. This could often cause confusion when switching between C# and VB.NET. The .NET Framework 4.0 addresses this issue by allowing VB.NET to create Lambda Expressions that don’t return anything. And, Lambda Expressions can now also contain statements instead of having to pass the logic to other methods as you had to do previously.

To write expressions that return nothing:

Dim lambdaNothing = Sub() Nothing
Dim lambdaSomething = Sub(Message) Console.WriteLine(Message)

To write expressions that contain statements:

Dim lambdaReturn = Function(i)
   If i >= 100 Then
      Return 3
   ElseIf i >= 10 AndAlso i < 100 Then
      Return 2
      Return 1
   End If
End Function

New C# Features

Dynamic Types and Dynamic Programming

C# should now support a new static type called 'dynamic'. This essentially allows for dynamic dispatch or late binding of the variable in question. For example, suppose you have two simple classes with a common-name method:
public class Coffee
   public int GetZing()
      return 1;

public class Juice
   public string GetZing()
      return "Orange";

You also have a method that returns one of the two object types:

private Object GetOneOfThem(int i)
   if (i > 10)
      return new Juice();
      return new Coffee();

You can then make a call to GetOneOfThem() without knowing what type you're going to have returned, but you can still attempt to call method names on it.

dynamic drink = GetOneOfThem(someVariable);

At runtime, GetOneOfThem() evaluates to either Juice() or Coffee() and then the corresponding method is called based on what the compiler resolves 'drink' to be. The above is a very simple example of dynamic programming—there is more to this. The underlying implementation of dynamic programming is the DLR—the Dynamic Language Runtime—which is what allows you to invoke things in a dynamic fashion. You can read more about dynamic programming and other new features in C#.

Optional Parameters

VB.NET has had this for a long time, and now C# gets it too—optional parameters in your function signatures.

private string GetMeaninglessDrivel(string drivelSeed="bork")

In the past, the lack of optional parameters in C# was overcome by overloading the method several times and calling the same common method from all overloads with different values being passed in. Optional parameters can help prevent unnecessary multiple overloads of methods and making a class unnecessarily complex.

Named and Optional Arguments

This feature is somewhat related to Optional Parameters. Suppose you have a method that has several optional parameters.

private void SaveTheseValues(int i=1, int j=2, int k=3)

If you wanted to pass in values just for j and k, but not i, you can now name the arguments that you are passing in instead of passing in values and skipping values with multiple commas.

So, instead of this:


You can do this:


Conclusion and Resources

That was a quick overview of what will probably be available to you in Visual Studio 2010 and the .NET Framework 4.0. To reiterate, you must keep in mind that because it is a CTP, not everything that you see will be exactly as it is when it is finally released (which is why I often discourage books that come out at the same time as the Visual Studio release - they're based on Betas and CTPs and so will not be completely reliable)

You can have a look at VS 2010 yourself if you'd like and if you can meet the hefty requirements for the Virtual PC image. You will need about 70 to 80 GB of hard disk space available, 2GB of RAM and a dual-core system at the least. The download is here.

The Parallel FX Library is also available as a CTP that works with the .NET 3.5 framework. You can download the Parallel FX CTP here.

Don't forget to have a read through the C# Future documentation as well for more information on the DLR.

Finally, you can also participate in the feedback process by submitting any bugs you find to the Microsoft Connect program for VS 2010.

Where Am I?

You are currently viewing the archives for October, 2010 at Naik Vinay.