Tuesday, October 30, 2007

New version of Gmail is Here!

New version of Gmail is already available in some Gmail accounts. If you see a link to a "newer version" at the top of the page, click on it and enjoy the new features:

  • Prefetching messages: When you load a page that contains a list of messages, Gmail will fetch them in advance so that when you need them, they'll be available instantly. Google said that Gmail will have a completely new JavaScript architecture that will bring a much better performance.
  • A new contact manager that will be shared with other Google apps (Google Docs, Google Calendar etc.)

Just to remind you, the previous gift from Google was a bigger mailbox's size.

Not all accounts got the new version, but during the next days I believe it will happen.

Enjoy!!

gmail

Technorati Tags:

WPF Composite Client

After the announcement about the death of Acropolis, Glenn just announced that the patterns & practices team will develop WPF Composite Client guidance for building composite client applications for .NET Framework 3.5 and Visual Studio 2008. This is not a new version of CAB . It is an entirely new set of  libraries and guidance, built from the ground up, targeting development of new WPF Composite applications. The target is to have all of the new guidance ship before the end of 2008.

Acropolis - The end

The Acropolis team just announced today that Acropolis will not advance from CTP to a supported release. They also announced that they want to help customers who'd like to take Acropolis into production be successful until an alternative is available.
The good news is that all the great work the Acropolis team did will be rolled out in the future versions of .NET and also used for guidance and best practices for building WPF Composite Clients.

Saturday, October 27, 2007

Data Dude: Synchronize vs Refresh

What the difference is between the "Refresh" button in "Solution Explorer" and the "Synchronize" button in "Schema View?

I was confused too, until I read Gert's post about it.

Synchronize - refers to synchronization of state between the Solution Explorer and Schema View.

Refresh - cause a complete reload of all schema objects (reading all files from links from the project file); parse the fragments and execute them against the design validation database.

Technorati Tags:

Code Analysis in VS 2008

VS 2005 introduced internal static analysis tools. This helps you to write secure and quality code.

Visual Studio 2008 has new Code Analysis features:

  • Code Metrics - This gives you the ability to dig deep to find those un-maintainable and complex hotspots. Code Metrics will ship with five metrics - Cyclomatic Complexity, Depth of Inheritance, Class Coupling, Lines of Code and Maintainability Index.
  • Analysis improvements:
    • Support for analyzing anonymous methods and lambda expressions
    • Reduced noise in existing analysis and the ability to skip over tool generated code
    • New analysis, including additional rules around security, globalization, maintainability and spelling.

 

To generate code metrics, simply do the following:In Solution Explorer, right-click on your solution/project and choose Generate Code Metrics

runCM

After generation you'll get the Code Metrics Results window and a tooltip on every column that explain the result. The Maintainability Index column includes a maintainability indicator light that changes based on the maintainability of the code. Green indicates good maintainability, yellow indicates moderate maintainability, and red indicates poor maintainability.

cmResults

 

Technorati Tags: ,

Friday, October 26, 2007

My session at Dev Academy 2007

Do you want to know how VSTS for database professionals helps you to take control on your database change? or how you can ensure you software quality? How can you write and execute unit tests for your database objects? devAcademy

You can get the answers and even more details and great features in the next Developers Conference here in Israel - Developer Academy 2.

I will be giving a there a session about VSTS for database professionals. If you work with databases then you will want to see the new capabilities offered by the latest addition to Visual Studio Team System from Microsoft. In this session, you will learn how this product will change the way you work with databases forever; you will get a look at how Visual Studio Team Edition for Database Professionals is used to help with Database development, Database Unit Testing, Database Refactoring, Code-Analysis for Database and Database deployment.

If you want to see more, or you have a question - post a comment.

See you there!

VS 2008 VPCs will expire on Nov 1st 2007

If you are using the VPC provided by Microsoft to evaluation Visual Studio and Team Foundation Server 2008 Beta2 be aware it will expire Nov 1st. 

See Jeff Beehler's post for more details.

Wednesday, October 24, 2007

Build a labeled version with TeamBuild

This is the 3rd post in the series of posts about MSBuild. You can read them at:

  1. Introduction to MSBuild.
  2. Create custom task to MSBuild - step by step.

As you know, TeamBuild builds the latest version by default. At the Target "CoreGet" in the MSBuild script (you can find it at Microsoft.TeamFoundation.Build.targets file), it gets the latest version from source control to the local workspace on the build machine and build the source.

To build a labeled source you have to set a value to the Version property of the Get task in this target.

So, all you need to do is to override the CoreGet target in the TfsBuild.proj file (it's better than override it in the target file because if you do so, this change will affect all builds on the machine...):

   1:  <Target Name="CoreGet"
   2:        Condition=" '$(IsDesktopBuild)'!='true' "
   3:        DependsOnTargets="$(CoreGetDependsOn)" >
   4:   
   5:      <!-- Get all the latest sources from the given workspace-->
   6:      <Get Condition=" '$(SkipGet)'!='true' "
   7:          Workspace="$(WorkspaceName)"
   8:          Recursive="$(RecursiveGet)"
   9:          Force="$(ForceGet)"
  10:          Version="$(VersionToBuild)" />      
  11:  </Target>

The property in line 10 is the property that do the work...


You can declare the $VersionToBuild variable at the PropertyGroup element or by passing this value from the .rsp file. The easiest way is to declare it at the PropertyGroup element.


   1:  <PropertyGroup>
   2:      <VersionToBuild>M_1.0.0.223</VersionToBuild>
   3:  </PropertyGroup>

That's all!


Enjoy.


Technorati Tags: ,

Open source at Microsoft

There is new open source site from Microsoft.

Microsoft opened a number of sites to host open source projects like GotDotNet, CodePlex, and now this one.  This site doesn't replace CodePlex. This site is intended to provide information about Microsoft and open source in one place, serving as a gateway for information about open source engagements and activities across Microsoft.

Technorati Tags:

10 Warning Signs of Project Failure

This is a great article that outlines the 10 signs that a project is going to fail which written by Allen Bernard.

What are the signs you agree with? I think that Undefined or poorly defined project requirements and lack of or poorly developed budget forecast are the real problems.

Technorati Tags:

Astoria DataSource Extender

PhaniRajuYN posted a very interesting post about Astoria DataSource Extender. (You can read my Getting Started With Astoria post to get more details about Astoria). The main issue is that it's a "Database in the cloud", which means that your database is hosted on the Web.

PhaniRajuYN Extender helps one retrieve data and post data to a database on Astoria using JavaScript.
The Extender encapsulates its own Server-Side handler so that  you don't have to write a Server-Side proxy to avoid Making Cross-Domain Requests from the Client browser.

You can read the post and download the source and sample from here.

Saturday, October 20, 2007

How to prevent SQL injections

Many applications include code that looks like:

   1:  string sqlStmt = "SELECT * FROM USERS WHERE UserName= '" + un + "' AND Password='" + pwd + "'";

Admit it...it's ugly, but you constructed SQL statements like this one.


The variables un,pwd are provided by the user. The problem with this SQL string is that the attacker can piggyback SQL statements in one of them.


What if the attacker enters this:


un = maor, pwd = 123456' OR 1=1. The following malicious statement is built:


   1:  string sqlStmt = "SELECT * FROM USERS WHERE UserName= 'maor' AND Password='123456' OR 1=1";

The statement will return all columns for all rows...Bad!


And what if the attacker enters this:


un=maor , pwd = 123456' DROP TABLE Users. The following malicious statement is built:


   1:  string sqlStmt = "SELECT * FROM USERS WHERE UserName= 'maor' AND Password='123456' DROP TABLE Users";

This builds SQL statement that queries for a user and then drops the users table.


What can you do prevent these attacks?


1. Quoting the input


Quoting the input is not a remedy, but its often proposed to solve the problem.


if we use the statement of:


   1:  string pwd;
   2:  pwd = pwd.Replace("'","''");

The code replaces single quotes with 2 single quotes in the input. The single quote is escaped and its render to invalid SQL statement. However its not perfect. If the statement has a integer field the attacker can use it to attack.


2. Use stored procedures


Many of us probably believe that the application is immune to SQL injection if we use stored procedures. WRONG!


When we enter the 123456' OR 1=1 to a parameter the sp will fail cause we cannot perform join across a stored procedure call. However, performing data manipulation is valid.


   1:  exec sp_getUser 'maor','123456' INSERT INTO Users Values('123','123')

This command will fetch data about the user and then insert a new row into the users table! What we can do? secure the stored procedure. How?



  1. Use quotename function for object names. It's built in T-SQL function that adds delimiters to object names to help nullify invalid characters.
  2. Use sp_executesql to execute sql statements built dynamically, instead of just concatenating a string. This makes sure no malformed parameters are passed along to the database server.

3. Never connect as sysadmin


If you see that your web application connects to the database as sysadmin account - its a BUG. Most of the web applications don't need the capabilities of a sysadmin to run; If there is a bug in the SQL statements and the application connects as sysadmin account, the attacker can: delete any database or table in the server; delete any table data; change data; alter tables; deletes log; and more... The potential damage is unlimited.


4. Build secure SQL statements


Instead of dynamically building a string, as shown in the bad examples above, use parameters. Anything placed into a parameter will be treated as field data, not part of the SQL statement, which makes your application much more secure.


Using parameterized queries is a three step process:


  1. Construct the SqlCommand command string with parameters.
  2. Declare a SqlParameter object, assigning values as appropriate.
  3. Assign the SqlParameter object to the SqlCommand object's Parameters property.

   1:  // 1. declare command object with parameter
   2:  SqlCommand cmd = new SqlCommand(
   3:      "SELECT * FROM USERS WHERE UserName= @UN AND Password= @PWD", conn);
   4:   
   5:  // 2. define parameters used in command object
   6:  SqlParameter param1 = new SqlParameter();
   7:  param1.ParameterName = "@UN";
   8:  param1.Value = userName;
   9:   
  10:  SqlParameter param2 = new SqlParameter();
  11:  param2.ParameterName = "@PWD";
  12:  param2.Value = password;
  13:   
  14:   
  15:  // 3. add new parameter to command object
  16:  cmd.Parameters.Add(param1);
  17:  cmd.Parameters.Add(param2);


Summary



  • Don't trust the user's input.
  • Be strict about what represent valid input and reject everything else. RegEx are your friend!!!
  • Use parameterized queries not string concatenation.
  • Connect to the database server by using a least-privilege account, not the sysadmin account.

Code secure!!!!


Technorati Tags: , , ,

Wednesday, October 17, 2007

.NET Framework Multi Targeting in Visual Studio 2008

One of the great features in Visual Studio 2008 is the ".NET Framework Multi Targeting".  This allows you to build applications targeting any of these frameworks using Visual Studio 2008:

  • .NET Framework 2.0 - released with Visual Studio 2005
  • .NET Framework 3.0 - released with Windows Vista
  • .NET Framework 3.5 - will release with Visual Studio Orcas

After I built a project targeted .NET framework 2.0 I encountered problem on a machine with .NET framework 2.0 installed.

It turns out that when installing Visual Studio 2008, it also install .NET framework 2.0 SP1. Hence, this means that when you target .NET 2.0 in Visual Studio 2008, you are really targeting .NET 2.0 SP1.

To run applications which built with Visual Studio 2008 and targeted to .NET framework 2.0, be aware that you need NET framework 2.0 SP1 on the application's host.

Saturday, October 13, 2007

Gmail's Storage Increases to 6 GB

gmailI read at Google Operating System blog that Gmail will increase the free storage gradually in the next days. On October 23, you'll get 4321 MB of storage, then the growth will slow down until January 4, when you'll have 6283 MB of storage.

That's really great.

Read more here.

Technorati Tags: ,

Linq to XML - Adding,Updating and Deleting data

The previous post about Linq to XML introduced how to query XML data using LINQ. LINQ allows us to not only query XML in a truly unique way, but also create XML documents in a very expressive manner. This post will talk about other operations on the XML: adding, updating and deleting data.

First, lets create a sample XML document:

   1:  XElement book = new XElement("Books", new XElement("Book",
   2:      new XAttribute("publisher", "O'Reilly Media, Inc."),
   3:          new XAttribute("price", "40$"),
   4:          new XElement("title", "Learning WCF: A Hands-on Guide"),
   5:          new XElement("authors", new XElement("author", "Michele Bustamante"))));
   6:   
   7:  book.Save("Books.xml");

Adding data to the XML document


Adding XML to the existing XML document is very simple, we need only construct our XML using a mixture of XElement and XAttribute types (there are other ways also...) and then add them to the document.


The following adds a new book:


   1:  XElement doc = XElement.Load("Books.xml");
   2:  XElement newBook = new XElement("Book",
   3:      new XAttribute("publisher", "Microsoft Press"),
   4:      new XAttribute("price", "45$"),
   5:      new XElement("title", "Introducing Microsoft LINQ"),
   6:      new XElement("authors", new XElement("author", "Paolo Pialorsi"), 
   7:          new XElement("author", "Marco Russo")));
   8:   
   9:  doc.Add(newBook);
  10:  doc.Save("Books.xml");

We must save the xml with the save method, because in LINQ to XML, no changes are made to the loaded XML document until that document is saved.


The XML document now is:


   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <Books>
   3:    <Book publisher="O'Reilly Media, Inc." price="40$">
   4:      <title>Learning WCF: A Hands-on Guide</title>
   5:      <authors>
   6:        <author>Michele Bustamante</author>
   7:      </authors>
   8:    </Book>
   9:    <Book publisher="Microsoft Press" price="45$">
  10:      <title>Introducing Microsoft LINQ</title>
  11:      <authors>
  12:        <author>Paolo Pialorsi</author>
  13:        <author>Marco Russo</author>
  14:      </authors>
  15:    </Book>
  16:  </Books>

Updating data


Updating XML data is also very simple; Just pick the element/attribute you wish to update and then set its new value.


   1:  XElement doc = XElement.Load("Books.xml");
   2:   
   3:  //obtain a single book
   4:  IEnumerable<XElement> singleBook = (from b in doc.Elements(
   5:                                        "Book")
   6:                                      where ((string)b.Element(
   7:                                      "title")).Equals("Introducing Microsoft LINQ")
   8:                                      select b);
   9:   
  10:  //update book, should only be 1
  11:  foreach (XElement xe in singleBook)
  12:  {
  13:      xe.SetAttributeValue("price", "39$");
  14:      
  15:      //use the ReplaceContent method to do the replacement for all attribures
  16:      //this will remove all other attributes and save only the price attribute
  17:      xe.ReplaceAttributes(new XAttribute("price", "32$"));
  18:  }
  19:   
  20:  doc.Save("Books.xml");

Deleting data


We simply have to get the object we want to delete and then delete it using the Remove() method.


   1:  XElement doc = XElement.Load("Books.xml");
   2:   
   3:  //obtain the first Book
   4:  IEnumerable<XElement> firstBook = (from b in doc.Elements(
   5:                                        "Book")
   6:                                        select b).Take(1);
   7:   
   8:  //delete book price
   9:  foreach (XElement xe in firstBook)
  10:  {
  11:      xe.Attribute("price").Remove();
  12:  }
  13:   
  14:  doc.Save("Books.xml");

Other way: we pass a lambda expression in as an argument to the Where extension method.

As you can see, Xlinq is really simple and great way to work with XML.


Enjoy!


Wednesday, October 10, 2007

Create custom task for MSBuild - Step by Step

This is the 2nd post in the msbuild posts series. The first post was an introduction to MSBuild and give you tasting of the basics.

In order to extend Team Foundation Build by plugging in your own logic and tasks, you must write a custom task and use it in your build script (the .proj file).

Custom MSBuild task must be implemented as a .NET class that implements the ITask interface, which is defined in the Microsoft.Build.Framework.dll assembly. You can implement your task in the following two ways:

  1. Derive your class directly from ITask and implement the methods on this interface. or
  2. Derive your class from the helper class, Task (an abstract base class that is a default implementation for BuildEngine and HostObject properties) which is defined in the Microsoft.Build.Utilities.dll assembly. Choosing this option makes it easier to log events from your task.

In both cases you must implement (ITask) or override (Task) it's Execute method. I override this mwthod with a very simple logic to just log a string value to the Build log as you see below.

Step 1 - Creating project

Create Class Library project with a class and a reference to Microsoft.Build.Utilities assembly. I'll derive the class from the Task abstract class and override the Execute method.

Step 2 - Writing the task

Execute function must return true if task has executed successfully otherwise it must return false. Now I will add my code to the Execute method - this is my logic which I want to be executed during the build process. I also add a property to the class (Message) and set an attribute to it [Required] (line 29) - this indicates that msbuild must pass a parameter to the task. The Log ( line 17,24) object I use is the LoggingHelper of the Build Utilities (defined at Microsoft.Build.Utilities.dll )

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Text;
   4:  using Microsoft.Build.Utilities;
   5:  using Microsoft.Build.Framework;
   6:   
   7:  namespace MSBuildTasks
   8:  {
   9:      public class MyTask:Task
  10:      {
  11:          private string message;
  12:   
  13:          public override bool Execute()
  14:          {
  15:              try
  16:              {
  17:                  Log.LogMessage(
  18:                      String.Format("This is the message from my task: {0}",
  19:                      message));
  20:                  return true;
  21:              }
  22:              catch
  23:              {
  24:                  Log.LogError("Error occured in my task!");
  25:                  return false;
  26:              }
  27:          }
  28:   
  29:          [Required]
  30:          public string Message
  31:          {
  32:              get { return message; }
  33:              set { message = value; }
  34:          } 
  35:   
  36:      }
  37:  }

Now compile the project.


Step 3 - Registering the task in MSBuild file


Now we need to import and register this custom task to the MSBuild file we want to extend (This is because MSBuild must know how to locate the assembly that contains the task class.) . We'll do it by editing the .proj file of the build and add a <UsingTask> element which is a direct child of root <Project> element.  This element has a TaskName attribute to get the name of the task class and an AssemblyFile attribute to get the name or address of the assembly where this class is implemented in.

<UsingTask 
TaskName="MSBuildTasks.MyTask" AssemblyFile="C:\Work\Projects\Samples\MSBuild\MSBuildTasks\bin\Debug\MSBuildTasks.dll"/>

Step 4 - Calling the task from MSBuild


Calling the task depends on the point in the build process where we want to call. We should choose the point in the process that we want to call the task and add the following under it:


   1:  <Target Name="MyTaskTarget">
   2:      <MyTask Message="Hi MSBuild" />
   3:    </Target>

Line 2 calls the task. The message here is the required parameter to pass to the task.


Step 5 - Running the MSBuild file


After all of that you should run the msbuild file.


This is my MSBuild file (.proj extension)

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<UsingTask TaskName="MSBuildTasks.MyTask"
AssemblyFile="C:\MSBuildTasks\MSBuildTasks.dll" />
<Target Name="MyTaskTarget">
<MyTask Message = "Hi MsBuild"/>
</Target>
</Project>

This is the output of the example.


msbuild


Enjoy!!


See you in the next post of the MSBuild series.




Technorati Tags:

Tuesday, October 9, 2007

C# Coding standards guideline

Scott Guthrie published another post in the link listing series. One of my favorites, is the link to the C# coding standards document, which was written by Juval Lowry from IDesign.

As Scott wrote:

Extremely useful if you are looking for a concise checklist of good suggestions to keep your codebase clean.

Technorati Tags: , ,

Monday, October 8, 2007

Reset autonumber (IDENTITY) column in SQL Server

Sometimes we need to reset the autonumber column in a table.

Using the DELETE statement is not enough. The statement only delete the data but not reset the identity column.

So how can we do it?

   1:  DELETE FROM tblName 
   2:   
   3:  DBCC CHECKIDENT (tblName,RESEED, 0)
 
 

 

Technorati Tags:

 



Sunday, October 7, 2007

I Search with Google’s experimental

Google recently added "Experiemental Search" to their list of Google labs options. Yesterday I started to search with it, and I found it quite interesting.

There are currently four different experimental search options. You just have to go to Google Experimental and select one of the four features that are currently tested.

  1. New ways to view search results: using specialized snippets, on a timeline or on a map. You can also access this feature without joining the experiment, using the view operator: just add view:info, view:timeline or view:map to your query.
  2. keyboard shortcuts: select a search result or move to the next result without using your mouse. You'll like it if you use shortcuts in Gmail or Google Reader.
  3. Two similar experiments: put the search navigation at the left/right of the page.

 

Timeline and maps view
Timeline view is a great way to sort results, especially for research queries. The results are grouped by years (or decades) and ordered from oldest down to the most recent. At the top of the screen is a linkable timeline that allows you to filter the results by selected time periods.

For example, I would like to know Microsoft's history.

I query: microsoft view:timeline and I got:

01

Keyboard shortcuts
The keyboard shortcut interface is just as it sounds, it provides a quick and easy way to navigate the search results using only our keyboard.

Key Action
J Selects the next result.
K Selects the previous result.
O Opens the selected result.
<Enter> Opens the selected result.
/ Puts the cursor in the search box.
<Esc> Removes the cursor from the search box.

02

left/Right hand search navigation

03

 

You can only choose one experiment at a time, it's easy to switch between them or deactivate them and there's an option to send your feedback.

Enjoy!!

Microsoft Israel link to my post

I am really excited. I notified that the opening page of Microsoft Israel mention my post about query XML using XLinq.

ms

It's great!

Query XML using XLINQ

LINQ to XML is a built-in LINQ data provider that is implemented within the System.Xml.Linq namespace in .NET 3.5.
It enables us do the following to XML data:

  • Read.
  • Construct.
  • Write.

We can perform LINQ queries over XML from the file-system, from a remote HTTP URL or web-service, or from any in-memory XML content.
LINQ to XML provides much richer (and easier) querying and data shaping support than the low-level XmlReader/XmlWriter API in .NET 2 and also much more efficient with usage of much less memory than the DOM API that XmlDocument provides. That's because it does not require you to always have a document object to be able to work with XML. Therefore, you can work directly with nodes and modify them as content of the document without having to start from a root XmlDocument object. This is a very powerful and flexible feature that you can use to compose larger trees and XML documents from tree fragments. Now that you have an overview of the XLinq's capabilities, the next few sections will examine the reading and writing features of XLinq before discussing the query capabilities.

01 (Figure and classes explanations are taken from XLINQ overview.doc)

Of the classes shown in this figure, the XNode and XContainer classes are abstract. The XNode class is the base for element nodes, and provides a Parent method and methods such as AddBeforeThis, AddAfterThis, and Remove for updates in the imperative style. For IO, it provides methods for reading (ReadFrom) and writing (WriteTo).
Although the XElement class is bottom-most in the class hierarchy, it is the fundamental class. As the name suggests, it represents an XML element and allows you to perform the following operations:

  • Create elements with a specified element name
  • Change the element's contents
  • Add, change, or delete child elements
  • Add attributes to the element
  • Save the element as an XML fragment
  • Extract the contents in text form

This post will introduce hoe to query xml and it is the first of series of posts regards to XLINQ.

Lets get a sense of how LINQ to XML works!

Query xml from URL

   1:  public static void GetRssFeedFromURL()
   2:  {
   3:      string url = "http://feeds.feedburner.com/MaorDavid?format=xml";
   4:   
   5:      // load the rss feeds into the XElement
   6:      XElement feeds = XElement.Load(url);
   7:   
   8:   
   9:      if (feeds.Element("channel") != null)
  10:      {
  11:          var query = from f in feeds.Element("channel").Elements("item").Take(10)
  12:                      select new { Title = f.Element("title").Value, Link = f.Element("link").Value };
  13:   
  14:          foreach (var feed in query)
  15:          {
  16:              Console.WriteLine(String.Format("Feed title: {0}",feed.Title));
  17:              Console.WriteLine(String.Format("Link: {0}",feed.Link));
  18:          }
  19:      }
  20:  }

XLinq is an XML query language that inherits from the LINQ query foundation. You can use it to query XLinq objects such as XElement, XDocument, etc using LINQ query facilities.

We start by loading the XML into memory using the Load() method of the XElement class. (Line 6).


After loading the XML , the next step is to retrieve all items (Line 11) and now you can query and iterate the results as described in my previous posts.(Var keyword, Getting started with Linq).

Very simple! This example load an XML from URL. What if you want to query XML from the file system? Nothing changed beside the uri parameter to load into the XElement. (Line 6)


   1:  public static void GetRssFeedFromFile()
   2:  {
   3:      string path = @"C:\Work\Projects\Samples\VS2008Samples\LinqToXML\Maor Davids Blog.xml";
   4:   
   5:      // load the rss feeds into the XElement
   6:      XElement feeds = XElement.Load(path);
   7:   
   8:   
   9:      if (feeds.Element("channel") != null)
  10:      {
  11:          var query = from f in feeds.Element("channel").Elements("item").Take(10)
  12:                      select new { Title = f.Element("title").Value, Link = f.Element("link").Value };
  13:   
  14:          foreach (var feed in query)
  15:          {
  16:              Console.WriteLine(String.Format("Feed title: {0}", feed.Title));
  17:              Console.WriteLine(String.Format("Link: {0}", feed.Link));
  18:          }
  19:      }
  20:  }

 

As you can see, all the code snippets presented above are fairly simple. Once the XML loaded into the LINQ to XML API, you can write queries over that tree. The query syntax is easier than XPath or XQuery.

Enjoy!!

Friday, October 5, 2007

Operations Guidance for Team Foundation Server

Do you want more guidance on daily operations in Team System?

Microsoft just released the Team Foundation Operations Guidance to address the issue of planning the installation and operation of a Team Foundation.  It also covers monitoring, topology, operations plans, users and groups, where the configuration information is, and backup/restore planning.

Check it out here:  http://msdn2.microsoft.com/en-us/library/bb663036(VS.80).aspx

Thursday, October 4, 2007

Getting started with Astoria

Few weeks ago, the CTP refresh for VS 2008 Beta 2 of Astoria was released. Astoria is a really cool project based on .NET 3.0 (WFC), Entity Framework to provide pure HTTP access to SQL Server data.In order to play with it, first of all you need to install the following:

After installing all we need, we can create out first project - this post will describe the steps you need in order to do that.

Create new Web Application Project:

1

After I did it, I need to add new ADO.NET Entity model. On the Project menu, click 'Add new item' and select the ADO.NET Entity Data Model.

2

Now, the wizard will start. Select: Generate model from database.

3

Next we'll save the connection info

4

I checked the option to add connection string to web.config and that's what I got there:

<add name="NorthwindEntities" connectionString="metadata=~/bin/NorthWind.csdl|~/bin/NorthWind.ssdl|~/bin/NorthWind.msl;
provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\sqlexpress;Initial Catalog=Northwind;
Integrated Security=True&quot;"
providerName="System.Data.EntityClient" />

The next step we select the objects we want. I choose Tables only.


5


What we got so far? .edmx file was added to our project, which is the schema.


6


Next step we should add and setup Astoria service. We'll do it from the Project menu --> Add new item.


7


New class was generated, it's not full cause we should select the type of the service.


8


I added the NorthwindModel.NorthwindEntities type. (NorthwindModel is the model I generated)


9


Now everything ready to compile...


After compilation, I can browse to the service I created. Look what I got:


10


The service describes the schema with the object I selected (Tables only).


How can I query the service? For example, if I want all the categories, I'll change in the address in my browser to: http://localhost:58889/NorthwindWebDataService.svc/Categories and I got all the categories:


(localhost:58889 is on my computer off course, change your host:port to match yours)


11


Amazing....


What about query it from asp.net app? There is a class that comes with the Astoria samples that provides a class and series of methods to create a more encapsulated approach to calling an Astoria web data service. You can find it at the installation folder.


What if I want to query the service to get the customers order by contact name:


http://localhost:58889/NorthwindWebDataService.svc/Customers?$orderby=ContactName


and what if I want the top 10 records:


http://localhost:58889/NorthwindWebDataService.svc/Customers?$orderby=ContactName&$top=10


Conclusion


Astoria is set to provide the developers a richer way of interacting with data on the server. The syntax is easy and there is a more structure API on the way for ASP.NET AJAX.


 


Technorati Tags: ,

Wednesday, October 3, 2007

Microsoft to release .NET Framework Library Source Code

Scott Guthrie just made an exciting post, starting with .NET 3.5 and VS 2008 the .NET libraries will have source available! 

One of the things my team has been working to enable has been the ability for .NET developers to download and browse the source code of the .NET Framework libraries, and to easily enable debugging support in them.

Today I'm excited to announce that we'll be providing this with the .NET 3.5 and VS 2008 release later this year.

Anyone who accepts the Microsoft Reference License will be able to browse and view the source code. The initial publication will include the BCL (System, System.IO, System.Collections, System.Configuration, System.Threading, System.Net, System.Security, System.Runtime, System.Text, etc), ASP.NET (System.Web), Windows Forms (System.Windows.Forms), ADO.NET (System.Data), XML (System.Xml), and WPF (System.Windows).

Read all about it here:

http://weblogs.asp.net/scottgu/archive/2007/10/03/releasing-the-source-code-for-the-net-framework-libraries.aspx

Here's a little more by Shawn Burke:

http://blogs.msdn.com/sburke/archive/2007/10/03/making-net-framework-source-available-to-developers.aspx

Technorati Tags: ,

Tuesday, October 2, 2007

EntLib Contrib September 2007 Release

entlib EntLib Contrib is a community-developed library of extensions to the patterns & practices Enterprise Library.

The latest release of EntLib Contrib is Enterprise Library Contrib September 2007.

What's new? Per Tom Hollander:

  • Data Access Application Block extensions:
    • MySql, SqLite and SqlEx providers.
  • Exception Handling Application Block extensions:
    • SqlException Wrap Handler.
  • Logging Application Block extensions:
    • LogParser.
  • Policy Injection Application Block extensions:
    • PostSharp4EntLib.
    • New matching rules: And, Or and Not.
    • New call handlers: CursorCallHandler, OneWayCallHandler, SynchronizedCallHandler, ThreadSafeCallHandler, TransactionScopeCallHandler.
  • Validation Application Block extensions:
    • New validators: CollectionCountValidator, TypeValidator<T>, ObjectValidator<T>, EnumDefinedValidator.
    • Designtime enhancements: Lightweight type picker, Test command.
    • Other extensions: Default validators, Argument Validation, ExternallyConfigurableObjectValidator.

Monday, October 1, 2007

Query types using LINQ

It's great. It's so beautiful. I really like it.

Reflecting types using LINQ.

How can we do it?

We can use Reflection of course, but with LINQ it shortest and simplest.

Declare "Type" object , assign the class you want to query and query with LINQ.

Example 1:

To get all methods of a class:

   1:  Type tPerson = typeof(Person);
   2:  var methods = from method in tPerson.GetMethods()
   3:                select method;
   4:   
   5:  Console.WriteLine("All methods:");
   6:  foreach (var m in methods)
   7:  {
   8:      Console.WriteLine(m.Name);
   9:  }



 


Example 2:

To get all methods that returns "int", use the "where' clause:


   1:  var ints = from method in tPerson.GetMethods()
   2:                where method.ReturnType == typeof(int)
   3:                select method;
   4:   
   5:  Console.WriteLine("All methods that returns int:");
   6:  foreach (var intType in ints)
   7:  {
   8:      Console.WriteLine(intType.Name);
   9:  }