Visual Studio - Database Project Not Loading

Have you ever created a Database project and after some time you are not able to load it in the Visual Studio? Probably you might be getting following error:

An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

The database project requires an active database connection to load at design time. Probably it uses that to compile/verify scripts. The problem here is Visual Studio is not able to connect to any such instance. Following are few solutions (these worked for me)

  1. Make sure the instance to which you want to connect is running and allows remote connections.
  2. After performing step 1, if it is still not loading then you may need to start the SQL Browser Service. Make sure it’s running.
  3. If the problem is still there, it has to be fixed from Visual Studio itself. Actually database project do not store to which instance it can connect. It’s a Visual Studio setting. In VS2008 go to Tool > Options > Database Tools > Design-time Validation Database > Connection Options. Specify your instance name here like “.\SQLEXPRESS”

If the problem is still there post it to MSDN forums :)

Ankit

Eating Exceptions… eeehhhh!

Following are few points you need to take care when you decide to eat an exception. These are very much specific to C# language.

a. Limit the code block. Attempt to wrap one or two statements within try.

b. If an exception is eaten, log details to some logging mechanism. In short never write empty catch catch(Exception) {}.

c. Never eat exception that indicates some bad behavior of code execution like - ArgumentNullException,

NullReferenceException,

ArgumentNullException,

InvalidCastException,

InvalidOperationException,

AccessViolationException, etc;

d. There is a big difference between throw and throw exeception statements. This is in terms of resetting stack trace which the later does. If you are writing a framework or want to hide your internal implementation use throw exception, otherwise use throw only.

- Ankit

Let’s Digg into Google Maps

The Web would not be so simpler and interactive without Ajax. This technology makes Web applications pleasant, interactive, quick responsive and light weight. Take any of the online map applications, no matter whether it is Yahoo Maps, Google Maps or Windows Live Local, and you will find awesome precession, cutting edge technology (beyond DHTML, XML and JavaScript) well managed data. Being software developer, these always attract me and I want to understand the scene behind those best software architectures/implementations. Over the last few days I was studying (hacking) Google maps and wanted to see how it works? Here are my investigations.

Tiles: The very first observation is – not whole map is fetched at once. Instead the entire map is divided into tiles and a series of Ajax requests are fired to retrieve some part of the actually map. As soon as a tile is fetched it is displayed at its position. Their position is well calculated no matter user drags the maps while requests are on the way. The benefit here is, the user interface remains responsive and it makes user eager to analyze an area of map as soon as it’s available.

Pune-Google-Map.jpg
(more…)

Windows CardSpace: FAQ for ASP.NET Developers

Few frequently asked question for ASP.NET developers:

  1. The Identity Selector dialog box is displayed only for SSL protected pages. Therefore you are required to deploy your application on a Web server and install a SSL Certificate.
  2. Windows CardSpace does not work with Self Signed Certificates and will die horribly. These certificates do not have CRL field. It contains a URL that CardSpace will check for the revocation list.
  3. For ASP.NET developers there is Toolbox control written by Christian Arnold. Add this to your Toolbox and you won’t need to write a single line of code. Watch demo.
  4. When you use CardSpaceLogin controls you must run application over SSL. The application pool also need to be run under Local System’s identify; otherwise w3wp.exe process will not be able to retrieve server’s private key. In such case you may end up with error stating “Keyset does not exist”. Note: This is not advisory if the application pool is shared with other Web applications. [ Edited: Refer Barry Dorrans comment for more details.]
  5. When using Information cards there is nothing like passwords.
  6. CardSpaceLogin controls are integrated with your identify providers such as Forms Authentication. For example: If you use Information Card to register a user, his details are reflected in the identify source.

TFS – Free Text search in History Objects

It’s a best practice to add comment when you do check-in to the source control. A text comment is associated with the change you made to the item. Some of the times you need to find a particular comment, but the View History tool available with Visual Studio/TFS is limited that you can’t make a search in the history results. Say you want to find all check-ins by a particular user :(

History Tool in Visual Studio 2005

Here comes the purpose of this small add-in. It provides search within history comments and find a particular change-set instead of traversing the whole list. The plug-in goes one step forward and facilitates free text search in change-set fields. For example you can use change-set id, username or even date-time as search keywords!!!

The major steps involved in developing this add-in are:

  1. Writing an add-in for Visual Studio 2005,
  2. Getting file history from Team Foundation Server (TFS),
  3. Look for the selected item in the Visual Studio IDE,
  4. Free text search along with the tools to compare two files.

(more…)

Think & Implement at Light Speed!

If you got an ‘idea’ that can drive business, implement it right away before someone snatches it from you and publishes the implementation, especially over the Internet.

That’s what happened with me. I had a thought of building ‘code-history’, history of each line of source code file. Typically when you look at the source control, you see file history. Actually it’s not directly associated with source code file; it’s first coupled to the change (change-set) you made and then linked to the file. So, the idea was to build Code History by combining two typical file operations: 1) File History and 2) File Diff technology. And drill down till you get the version where selected code was first introduced.

Orcas, next version of Visual Studio, features the same named – Annotate:

“Annotate is an Orcas feature that allows developers to inspect a source code file and see at line-by-line level of detail who last changed each section of code. It brings together changeset data with difference technology to enable developers to quickly learn change history inside a source file. You can answer the questions “which version of the file introduced this section of code?” or “who left this buffer overrun in the code?!” Subversion users may recognize this as the ‘Blame’ command.”

- Explained by Orcas Team

In simple words, I lost it :(

This is not a single instance, earlier the concept of Flickr Maps stroke to my mind and while I was planning (for few weeks) the scope of the concept, they launched :( .
No doubt, they are ahead, but not much. I’m just around the corner!

Lessons I learnt:

  • Internet is Big Boss that knows every thing. If you have an idea, first search for the same thoroughly.
  • If your thought is unique, carry out Proof of Concept right away. I mean “right away“.
  • In case you don’t want to implement, write a ‘Blog post’ to claim (or go for patent). Or give it to me I’ll write.
  • Think much faster (much much faster at what pace I do currently).

The exponential growth of Internet has made world’s thinking/inventions much faster then what happened in previous centuries. Inventions are much closer to each other with a thin line of separation. The half-life of our knowledge is decreasing and Humans have to survive!

Thanks!

- Ankit

[Inputs from ‘Chiku’ - aka Chirag Maharaj:

The records breakers are just a second ahead then the runners up then also the money difference in them is more than 10 times and even the glory they receive is 100 times more than runner up; though the diff was just one second!!!

So you to be the winner, you have to be just one step ahead. A little hard work could make u at top!
]

Preview: LINQ

Hmmm… a new tool in my hands
… and following equation makes me crazy about it…

C# 2.0 + ADO.NET = LINQ = C# 3.0

In simple words Language Integrated Query (LINQ) exposes the power of SQL queries within C# syntax. This technology along with its tools allows you to connect to SQL database, extract metadata, build typed datasets/classes (using C# Generics) and make you use them along with C# syntax using just two lines of code. And not necessarily SQL databases, it can execute on any collection type.

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums =
     from n in numbers
     where n < 5
     select n; Console.WriteLine("Numbers < 5:");
foreach (var x in
lowNums)
{
    Console.WriteLine(x);
}

Have a look at Linq Project @ MSDN and 101 Samples all to sense this. Here in this short -n-simple post I’m just showing how to do things for databases stored as *.mdf files and generate wrapper classes.The LINQ preview includes SqlMetal.exe, a utility to auto-generate a strongly-typed C# DataContext class file from an SQL Server 2000 or 2005 database’s metadata with this execution syntax:

$>sqlmetal.exe /namespace:NWind /language:csharp /code:Northwind.cs “c:\ Northwind.mdf”

- Ankit

Webservices PowerPoint Presentation

My presentation on WebServices Basics is available for download to the *valuable visitors* of my blog. Here is the content:

  • Web services - Definition: A web service is a collection of protocols and standards used for exchanging data between applications or systems.
  • Characteristics
  • Demo: Writing a simple WebService in Visual Studio 2005 & Consuming WebServices
  • Technologies: XML (eXtensible Markup Language), SOAP (Simple Object Access Protocol), WSDL (Web services description language), UDDI (universal description, discovery, and integration)
  • SOAP: SOAP is an open protocol specification defining a uniform way of performing RPCs using HTTP as the underlying communications protocol with XML for the data serialization.
  • Drilling inside SoapHttpClientProtocol class
  • Advantages of Web services
  • SOA – Service Oriented Architecture, Four Tenets

Thanks,

~ Ankit

Fetching file history from TFS : the code way

These days I’m writing a tool for Visual Studio that integrates with Team Foundation Server. This post is about how to retrieve/fetch history of a file from source control server using TFS-SDK. Following function takes server name and file path as input and returns an enumerator holding Changeset objects.

public static IEnumerable FetchHistory(string serverName, string filePath)
{
TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer(serverName);
VersionControlServer vcs = tfs.GetService(typeof(VersionControlServer)) as VersionControlServer;
ExtendedItem[] itemArray1 = vcs.GetExtendedItems(filePath, DeletedState.NonDeleted, ItemType.Any);

if ((itemArray1 == null) || (itemArray1.Length == 0))
throw new Exception(“There are no items.”);

ExtendedItem item1 = itemArray1[0];
IEnumerable enumerable1 = vcs.QueryHistory(filePath,
VersionSpec.Latest, item1.DeletionId,
(item1.ItemType == ItemType.Folder) ? RecursionType.Full : RecursionType.None,
“”, new ChangesetVersionSpec(1),
VersionSpec.Latest, 0×7fffffff, true, false);
return enumerable1;
}

To compile this successfully you also need to add references of following two assemblies found at [VS installation directory]\Common7\IDE\PrivateAssemblies\:

Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.VersionControl.Client.dll

Call to this function should be made as follows:

FetchHistory(“[serverName]”, “$/Project1/Class.cs” );

- Ankit

3D Full Screen Window and Dynamic XAML Sample with WPF

One nice feature of WPF (Windows Presentation Foundation, .Net 3.0) is the integration of 3D library with the existing framework. Today I worked with Viewport3D class. This class handles it all for managing 3D views. The “Hello World” example I coded here basically demonstrates three features:

  • Loading XAML dynamically at runtime
  • Playing with 3D objects using Viewport3D and make them rotate using mouse.
  • Creating transparent and full-screen windows

Let’s drill down to the technical details of above three aspects:

Firstly, loading XAML runtime can be achieved using System.Windows.Markup.XamlReader class. The Load function takes a stream object (containing XAML source) and return appropriate UI control. Actually, it returns the root control in the stream.

FileStream fs = File.OpenRead(fileName);
this.view3D = (Viewport3D) System.Windows.Markup.XamlReader.Load(fs);

Secondly, the class Viewport3D does it all for you to handle 3D objects. Here we have just hooked mouse events that allows rotation of 3D object in all directions. Moreover you can zoom in/out using right mouse button. Thanks Daniel for writing TrackBall class.

Lastly, setting few parameters as below we can make a Window appear transparent and full-screened:

this.win = new Window();
win.Content = view3D;
win.ShowInTaskbar = false ;
win.Background = Brushes.Transparent ;
win.AllowsTransparency = true;
win.WindowStyle = WindowStyle.None ;
win.WindowStartupLocation = WindowStartupLocation.CenterScreen ;
win.WindowState = WindowState.Maximized;
win.Show();

Well, I guess that’s enough for the first WPF post.
Download the source code for sample application: Load-3D-XAML-Runtime.zip

Thanks for reading.
~ Ankit

IE extensions/add-on – the simplest way (context menu)

I love writing extensions for applications and filling gaps in between making the world simpler (interacting with each other, giving users flexibility in switching from one application to another.) The power of any application (especially Internet Browsers) lies in how features enriched it is. One of the way to achieve this is to lay down extensible architecture and promote developers to write extensions for you application. Moreover such architecture should provide

  • the simplest method to write an extension in few seconds (“hello world” example)
  • more flexible in term of autonomy to developer for by exposing a rich set of API, that they can code almost everything,
  • and the last, limiting them touching sensible data of user.

Well, the power of FireFox lies in more than thousands of extensions that it provides. This could also have been for Internet Explorer, if Microsoft has provided detailed documentation and samples for Internet Explorer when they released IE 5. Over the years Microsoft had always concentrated on the Web development front of IE, not on the extensibility part of it even though providing great ways to extend.

Let’s go through Internet Explorer for writing the simplest extension in just 5 minutes. So, what we want to do? Here I;m showing how to access Html DOM and change it on the fly. All you need to know is simple JavaScript and basic programming concepts. Here are the steps on MSDN that details adding a context menu to Internet Explorer.

(more…)

Forcing Download on Web page

Here I’m explaining how to create a webpage that offers download on button click event, instead of showing a direct link to the download file. The following C# piece of code when inserted in button click event on ASP.net web page, gives you an effect of dynamic download, hiding download URL.

HTTP requests and responses travel along with lot of headers, just like meta-data for the request/response. Here is the list of some of them, Response Headers. Following example makes use of them. The method implemented here is just for the sake of example, and not to be used on Web Servers. Problem here is we are reading one byte, writing to response and flushing the response again-n-again. Here for every single byte, a packet is created and sent to the client, creating packet flood! Using a buffer of at least 1000 bytes before flushing is recommended.

Response.Clear();
String fileNameToSend = “downloadTest.txt”;

//Make sure following file exists and it’s size is less than 2KB.
FileInfo file = new FileInfo( “C:test.txt” );
String value = “attachment; filename=”" + fileNameToSend + “”";
Response.ContentType = “application/octet-stream” ;
Response.AddHeader(“Content-length: “, file.Length.ToString());
Response.AddHeader(“Content-Disposition”, value );
FileStream fs = null ;
try {
   fs = File.OpenRead(“C:test.txt”);
   BinaryReader br = new BinaryReader(fs);
   while (true)
   {
       // EOF exception to exit loop, not a good way!
       Response.Write((char)br.ReadByte());
       System.Threading.Thread.Sleep(5);
       Response.Flush();
   }
}
catch {}
finally
{
   if (fs != null )
      fs.Close();
}
Response.End();

What more you can do with this?

  • allow users to download only one file at a time,
  • limit bandwidth for specific users, etc.

~ ankit

Outlook Hack : Empty subject warning

How many times you have forgot to write subject of emails you sent through Outlook?? The biggest blunder is Outlook doesn’t show any warning ! Here is a hack/macro for it.

Steps:

  1. Open your outlook
  2. Press Alt+F11. This open the Visual Basic editor
  3. On the Left Pane, one can see “Microsoft Outlook Objects”, expand this. Now one can see the “ThisOutLookSession”.
  4. Click on “ThisOutLookSession”.
  5. Copy and Paste the following code in the right pane.(Code Pane)
  6. Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    Dim strSubject As String
    strSubject = Item.Subject
    If Len(strSubject) = 0 Then
    Prompt$ = “Subject is Empty. Are you sure you want to send the Mail?”
    If MsgBox(Prompt$, vbYesNo + vbQuestion + vbMsgBoxSetForeground, “Check for Subject”) = vbNo Then
    Cancel = True
    End If
    End If
    End Sub
  7. Now save and close the VB Code editor. From now on , this macro will make sure you do not make the mistake of sending a mail without subject.

~ Ankit