Showing posts with label Visual Studio 2008. Show all posts
Showing posts with label Visual Studio 2008. Show all posts

Wednesday, August 13, 2008

Visual Studio 2008 Service Pack 1 and .NET Framework 3.5 Service Pack 1

Introduction

Visual Studio 2008 and the .NET Framework 3.5 enable developers to rapidly create connected applications that deliver high quality and rich user experiences. Visual Studio 2008 enables organizations of every size to rapidly create secure, manageable, and reliable applications that are optimized for Windows Vista™, SQL Server, the Microsoft 2007 Office system and the Web.

Visual Studio 2008 Service Pack 1 (SP1) and .NET Framework 3.5 SP1 continue Microsoft’s investment in market leading development tools and developer platform. SP1 addresses issues that were found through a combination of customer and partner feedback, as well as internal testing. These service packs offer customers improvements in responsiveness, stability and performance.

Overview

.NET-based Windows application development benefits from increased Windows Presentation Foundation (WPF) designer performance and updated components for Visual Basic and Visual C++ (including a MFC-based Office 2007 Ribbon).  Web development improvements include enhanced the client-side script tooling (JavaScript IntelliSense). In addition to IDE performance improvements SP1 fully supports SQL Server 2008 and the ADO.NET Entity Framework.

The .NET Framework 3.5 Service Pack 1 (SP1) delivers more controls, a streamlined setup, improved start-up performance, and powerful new graphics features for client development and rich data scaffolding, improved AJAX support, and other improvements for Web development. Additionally it introduces support for the ADO.NET Entity Framework and ADO.NET Data Services, which simplify data access code in applications by providing an extensible, conceptual model for data from any data source and enabling this model to closely reflect business requirements.

Visual Studio 2008 SP1 delivers:

  • Improved WPF designers
  • SQL Server 2008 support
  • ADO.NET Entity Designer
  • Visual Basic and Visual C++ components and tools (including an MFC-based Office 2007 style ‘Ribbon’)
  • Visual Studio Team System Team Foundation Server (TFS) addresses customer feedback on version control usability and performance, email integration with work item tracking and full support for hosting on SQL Server 2008
  • Richer JavaScript support, enhanced AJAX and data tools, and Web site deployment improvements

The .NET Framework 3.5 SP1 delivers:

  • Performance increases between 20-45% for WPF-based applications – without having to change any code
  • WCF improvements that give developers more control over the way they access data and services
  • Streamlined installation experience for client applications
  • Improvements in the area of data platform, such as the ADO.NET Entity Framework, ADO.NET Data Services and support for SQL Server 2008’s new features

Additional Details

WPF and visual designer improvements

Cold startup performance improvement ranging between 20-45% depending on application size without needing to modify any code.

Additional WPF support for text and graphics, and media to deliver better performance. For example, effects like DropShadow and Blur were implemented using software rendering; with SP1 these are now implemented using hardware acceleration. Other examples include:

  • Text, especially when used in Visual and DrawingBrush, is substantially faster,
  • Scrolling improvements with Container Recycling, improved working set with TreeView virtualization
  • A much improved WriteableBitmap that enables real-time bitmap updates from a software surface,
  • Designer support for the event tab within the property grid for control events,
  • Toolbox support within source mode.

.NET Framework 3.5 SP1 Optimized Client Runtime

SP1 provides a .NET Framework install version that is optimized for .NET-based client applications. The size of this optimized runtime is less than 28 MB.

New ADO.NET Data Features

ADO.NET Entity Framework

The ADO.NET Entity Framework is the next evolution of ADO.NET, raising the level of abstraction at which programmers work with data, and allowing the database structure or data source to evolve without significant impact to the application code.

Rather than coding against rows and columns, the ADO.NET Entity Framework allows the definition of a higher-level Entity Data Model over your relational data, and allows developers to then program in terms of this model. Developers get to deal with the data in the shapes that make sense for the application, and those shapes are expressed in a richer vocabulary that includes concepts like inheritance, complex types, and explicit relationships.

Use LINQ to Entities with the Entity Framework for queries that help create easy to maintain code that retrieves and works with strongly typed data objects or business entities.

ADO.NET Data Services

The Microsoft ADO.NET Data Services framework provides a first-class infrastructure for developing the next wave of dynamic internet applications by enabling data to be exposed as REST-based data services that can be consumed by client applications (ASP.NET, AJAX, Silverlight) in corporate networks and across the internet. Easily build applications using a comprehensive set of Microsoft .NET libraries and client components, accessing data through uniform URI syntax and using standard HTTP verbs to operate on the resource.

ADO.NET Data Services provides a framework to build data services for relational data sources, such as Microsoft SQL Server, MySQL, DB2, and Oracle, using the built-in support for the ADO.NET Entity Framework, or for non-relational data sources using the pluggable provider model.

TFS improvements

A number of improvements have been made to Visual Studio Team System 2008 Team Foundation including:

Version Control

  • Simplified the user experience through cleaner “Add to Source Control” dialogs, drag and drop support to the Source Control Explorer and a much easier to use “Workspace” dialog for working folder mappings.
  • Version control now automatically supports non-solution controlled files.
  • Various changes to the Source Control Explorer such as a new checkin date/time display column, local path hyperlink support and en editable source location field.

Work Item Tracking

  • Microsoft Office 2007 integration is now done using the standard Office “Ribbon” delivering a cleaner and easier to use integration to the different Microsoft Office 2007 products.
  • Email integration for work items and links for Team system Web Access to make it easier to use email as part of the development lifecycle.

Visual SourceSafe migration tool

  • The migration tool has been dramatically improved through many performance and reliability improvements. SP1 provides support for the elimination of namespace conflicts, automatic solution rebinding, improves timestamp coherency and increases the amount of migration logging information available.

Additional Features

  • Support for using SQL Server 2008 with Team Foundation Server.
  • Team System Web Access provides “live” links to work items and checkin emails. This improves the customer experience for users who do not use Team Explorer.
  • Scripting support for the creation of Team Projects.

Performance and scalability

  • With SP1 a large part of the focus was to improve the performance and scalability of Team Foundation Server through changes such as faster synchronization with Active Directory, improved checkin concurrency, a faster way to create source tree branches, online index rebuilding for less maintenance downtime and better support for very large checkin sets.
  • Improvements in the number of projects a server can support that make not only the scalability of the server better but also the client experience when connecting to a server with a large number of projects on it.

 

from http://msdn.microsoft.com/en-us/vstudio/products/cc533447.aspx

Tuesday, July 22, 2008

VSTS 2008 Team Foundation Server Power Tools - July 2008 Release

The Visual Studio Team System 2008 Team Foundation Server Power Tools is a set of enhancements, tools and command line utilities that improve the Team Foundation Server user experience.

The latest power tools release can be found here: TFS July 2008 Power Tools

See BHarry’s blog for an overview of all the great enhancements and make sure you download and install it.

The following tools are installed with the tfpt.msi package:

  • Command line tool (TFPT.EXE)
  • Team Explorer IDE menu additions
  • Build Notification tool
  • TFS Best Practices Analyzer
  • Process Template Editor
  • Work Item Templates
  • Custom check-in policies
  • TFS Server Manager
  • TFS Users tool
  • Alert Editor

Also available is the WssExt64Bit installer which provides the ability to install the Team Foundation Server WSS extensions into a 64-bit WSS instance. The RTM version of the WssExt installer that ships with Team Foundation Server 2008 does not support 64-bit WSS sites.

For more information, see Visual Studio Team System 2008 Team Foundation Server Power Tools.

Share this post :

Wednesday, June 4, 2008

VSTS 2008 Database Edition GDR June CTP

Yesterday, at TechEd 2008 Developer, Data Dude team announced the immediate availability of the first public CTP of the Visual Studio Team System 2008 Database Edition GDR (General Distribution Release).

 

The GDR is available now for download but before you install it, make sure read the installation requirements. If you have DBPro Power Tools installed, uninstall it first. AND you'll need to have Visual Studio 2008 Service Pack 1 Beta installed

 

 

From Gert's post:

What is in the GDR?

In addition to enabling SQL Server 2008 database projects, the GDR release incorporates many of the previously released Power Tools functionality as well as several new features. The new features include explicit separation of Build and Deploy, separation of Database and Server project, improved project reference support, T-SQL Static Code Analysis and integration with SQL-CLR projects.

Architectural changes

  • No more DesignDB; one of the most important architectural changes is that the Database Edition no longer requires a local SQL Server instance to host the "Design Database" to open and validate a database project.
  • Single model, everything is now loaded in a single model representation. The model now represents all object types, which removes the need to have certain objects represented as Pre or Post Deployment scripts. This means that for example logins, rules, defaults, asymmetric keys, symmetric keys, certificates, etc. are now schema objects and therefore fully participate in schema comparison and build/deploy. Pre or Post Deployment scripts still exist, but are only used to perform none schema object related operations.
  • The model is no longer 100% memory resident, in today's version all model information has to reside in memory, this change dramatically lowers the memory consumption of the product.
  • Provider based, the underlying implementation of the project system and schema model are changed to be provider based. Providers are refer to as "Database Schema Providers" or DSP's for short. The GDR release will ship with 3 providers supporting SQL Server: 2000, 2005 and 2008. However if you watch the Tech*Ed keynote this morning, you saw that IBM is working on a provider to support DB2 and there are others that are working on providers for other database management systems.
    • Providers are not restricted to relational database systems, in the future we will be adding providers that support dimensional and hierarchal data stores.

Project System

  • Database & Server project separation
    • We separated out the existing database project in to two project flavors: database and server. The server project represent those schema objects that are server wide, for example logins, linked servers, server side DDL triggers etc. Database projects represent the objects inside the user database. The split enables a team to define a standard a configuration for their SQL servers and reference it from their Database Projects. The goals is to have a single point of definition and to be able to share this definition between projects and deployments.
      • The separation is implemented using a property inside the project file. There are effectively 3 modes: server, database and hybrid. The hybrid project represents the overloaded project model as it exists today where server and database objects are mixed inside a single project. This model is there to support existing project upgrades.
  • Partial projects
    • Allow code sharing between projects by including files from a different project, where the code is included "as-is" from the originating project and the source code control ownership remains with the originating project. This enables code reuse between projects and while resulting in a single deployment unit.
  • Composite projects
    • Composite projects, enables database projects and/or .dbschema files to contribute to another project. This enables the separation of development roles and responsibilities and composition of Databases using multiple projects. It extends the existing database reference implementation, by allowing to contribute in to the same database, where the existing database projects have to represent 3 or 4 part name references.
  • Single sourcing of external artifacts
    • You can now create a reference to a SQL-CLR (VB.NET or C#) project, or the binary output of a project and turn it in to a ASSEMBLY inside the project. This enables single sourcing of artifacts that are developed outside the context of the database project. For the final release we will also allow references to XSD files which will become XML Schema Collections inside the database schema.

SQL Server 2008 Support

  • The GDR adds a new project for supporting SQL Server 2008. The June CTP has support of the new SQL Server 2008 data types, both intrinsic (date, datetime2, datetimeoffset, time), build-in SQL-CLR types (geography, geometry, hierarchyid), support for the new DML MERGE syntax and support for table typed parameters. The remaining SQL Server 2008 syntax and functionality will be added in future CTP's.

Build & Deploy

  • One of the other main changes in the GDR is the separation of the build and deployment process. Build now produces a single portable artifact file, a .DBSCHEMA file. The DBSCHEMA file is an XML representation of your complete schema. The DBSCHEMA is then fed in to the redistributable deployment engine.
  • The deployment engine now uses the exact same database model as Schema Compare, which guarantees the same results between the two parts of the system.

Refactoring

  • The biggest change in refactoring is the addition of a patented implementation of a feature named "Preservation of Intent". This enables the deployment of refactoring changes as intended by the user. For users this means that renames are deployed as renames not as drop/add statements, move aschemas as move schemas etc.
  • Besides that we are adding new refactoring types that we previously in the Power Tools:
    • Wildcard Expansion
    • Move Schema
    • Fully Qualify
  • And we are enabling extensibility for refactoring which enables users to develop and deploy custom refactoring types and targets.
    • Types are the refactoring operations, where targets are the artifacts you want to apply the refactoring operation to. An example of a refactoring type is: table split or upper case all keywords. An example of a refactoring target is an Reporting Services RDL file, which contains references to database schema objects, which if you change thos, you want to update them as part of the refactoring operation.

Schema Compare

  • Schema Compare now uses the same underlying database model as build and deploy, guaranteeing fidelity between the results. This allows the user to compare any combination of Database Projects (.dbprj), live Databases or .DBSCHEMA files.  So comparing project to project, project with a DBSCHEMA file, or a DBSCHEMA file with a live database.
  • We added the ability to limited the schema comparison based on object types (Object Type Filtering) and we added additional Ignore filtering options.
  • We also enabled the substitution of SQLCMD variables, allowing correct comparison when using SQLCMD variables for references or in other parts of your code.

T-SQL Static Code Analysis

  • T-SQL Static Code Analysis, and the accompanying MSBuild task, are now part of the main product.
  • And we added the ability to develop and deploy your own custom T-SQL Static Code Analysis rules.

Dependency Viewer

  • The Power Tools to view the dependency relationship between objects inside your schema, is now part of the base product.

Database Unit Testing

  • Database unit testing now supports execution of tests using different ADO.NET providers and it also enables unit testing when using multiple database projects.

• Data Generation

  • We made some general design-time enhancements Data Generation like adding support for undo/redo and separation of the population status into new display window.
  • The Foreign key generator can now be replaced by custom generator.
  • And we made some runtime enhancements, by default the Data Generator now uses the SqlBulkCopy interface to populate target tables, which results in a general performance improvement during data load time.
  • We also introduced the concept of Data Sinks which allow the user to register different outputs, for example we can generate data to files instead of to a live database, so data can be loaded out-of-band using BCP or BULK INSERT. 
  • And last but not least we were able to significantly trim the size of the .DGEN file. 

Public extensibility:

  • The last piece we changed in the GDR is to expose more extensibility points in to the system. In the GDR we are not allowing new providers to be plugged in this will be available in the next release, but we do allow users to extend the system by writing their own:
    • Data Generators
    • (Statistical) Data Distributions
    • Test Conditions
    • T-SQL Static Code Analysis Rules
    • Refactoring Types
    • Refactoring Target
  • We also made the deployment engine a redistributable component, so you can deploy DBSCHEMA files programmatically.

Tuesday, May 27, 2008

Microsoft Source Analysis for C#

Microsoft announce the public release of a new developer tool -  Source Analysis for C#.

Inside Microsoft this tool's name is StyleCop and it enforces code style guidelines on the code we write

Source Analysis comes with a set of default rules analyzers covering approximately 200 best practice rules. These rules are full compatible with the default layout settings in Visual Studio 2005 and Visual Studio 2008.

Specifically, these rules cover the following, in no particular order:

  • Layout of elements, statements, expressions, and query clauses
  • Placement of curly brackets, parenthesis, square brackets, etc
  • Spacing around keywords and operator symbols
  • Line spacing
  • Placement of method parameters within method declarations or method calls
  • Standard ordering of elements within a class
  • Formatting of documentation within element headers and file headers
  • Naming of elements, fields and variables
  • Use of the built-in types
  • Use of access modifiers
  • Allowed contents of files
  • Debugging text

After installation, Source Analysis can be run from within the Visual Studio IDE. You can set this up to be run as a part of your build process as documented here. Since this is plugged in as a MsBuild project you can use it in as a part of Team Foundation Build process as well.

 

Running Source Analysis:

sca1

And the results are:

sca2

 

Download it from: http://code.msdn.microsoft.com/sourceanalysis

Read full details:http://blogs.msdn.com/sourceanalysis/archive/2008/05/23/announcing-the-release-of-microsoft-source-analysis.aspx

Tuesday, May 20, 2008

Search File System Using LINQ

Do you want to search a file or file type in the file system ? Nice way to do it is using LINQ.

var files = from file in new DirectoryInfo(@"D:\temp").GetFiles()
where file.Name == "MyFile.txt"
select file;


Or even search after specific file extension :



var files = from file in new DirectoryInfo(@"D:\temp").GetFiles()
where file.Extension == ".txt"
select file;


Enjoy,



Maor

Saturday, April 26, 2008

Visual Studio 2008 Product Comparison Guide, v1.08 + Updates

A new version of the Visual Studio 2008 Product Comparison Guide is now available. Version 1.08 includes updates to a number or line items, but in particular it includes a lot of fixes in the debugging section and adds a section on 64-bit development features.

Wednesday, February 27, 2008

Stop Connecting To TFS Automatically On Visual Studio Startup

I often visit customers and work outside the office, means I work disconnected for a while.

It's laborious when I open VS (2005 or 2008) and waiting for VS to connect automatically to TFS.

Colin Beales has an excellent tip that explains how to stop Visual Studio from automatically connecting to a TFS server when it starts up.

  • Backup your registry
  • Navigate to Team Foundation key:
    • For VS 2005 navigate to: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\TeamFoundation
    • For VS 2008 navigate to: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\TeamFoundation
  • Add a registry key "AutoLoadServer" (type DWORD)
  • Setting the value to be 0 (Do not connect automatically or 1 to connect automatically).

Friday, February 15, 2008

Visual Studio Team System 2008 Database Edition Power Tools

Finally, the “DataDude” team announced the availability of the Power Tools for Visual Studio Team System 2008 Database Edition.

The release includes all the functionality that shipped in 2005 plus:

  • Command line SQL Static Code Analysis execution through MSBuild. This enables SQL Static Code Analysis to be an integrated part of Team Build!
  • Data Generation Wizard; allow users to create a new data generation plan by pointing at an existing database, the plan will be fully configured by the wizard to pull all data from the database using the Sequential Databound Generator. This way users can use an existing data set and only override columns which impose risks because of for example privacy concerns and save about half a day or more of configuring a data generation plan from scratch, one column at the time.
  • File based data generator; this allows you to insert the content of files in to the database (works for string and binary, not for XML yet).
  • XML based data generator; this allows you to generate XML based on an XSD (the XSD has to be provided as file right now, and cannot be selected from database or inherited from the data type).
  • Unique Regular Expression generator; this adds the ability to generator unique values using the RegEx String generator.
  • Refactoring Command Generator has been made available as a MSBuild task for better project build integration so it can be made part of the pre-build and pre-deployment stages in the project. This allows users to automated the results of refactoring to some degree in to the project.
  • Two new test conditions for Database Unit Tests
    • ChecksumCondition – Which you can use to verify that the checksum of the data set returned by a database unit test matches the checksum of an expected data set.
    • ExpectedSchemaTestCondition – Which you use to verify that the column names and data types of the returned data set match expected values.

Download page:
http://www.microsoft.com/downloads/details.aspx?FamilyID=73ba5038-8e37-4c8e-812b-db14ede2c354&displaylang=en

Installer download:
http://download.microsoft.com/download/f/b/8/fb8d1c0d-c0c4-4004-ab86-12396b2a3ee3/VSTSDB2008PT.msi

Documentation download:
http://download.microsoft.com/download/f/b/8/fb8d1c0d-c0c4-4004-ab86-12396b2a3ee3/Power Tools 2008.doc

In the following weeks I'll start to record screencasts and writing some posts about this release.

Enjoy!!

Friday, December 21, 2007

Team Foundation Power Tools for VS2008

Ed Hintz just announced the Team Foundation Power Tools for VS2008 are now available:

The Team Foundation Power Tools for VS2008 are now available here.  This is the first release of the Power Tools that work with VS2008.  We did not want to just deliver a warmed over version of the VS2005 Power Tools, so we included lot of new goodies in this release.

It includes:

  • Find In Source Control
  • Quick Label
  • Process Template Editor
  • Open in Windows Explorer
  • Team Build Notificationapplet
  • More commands...

Click here for download.

Sunday, December 16, 2007

No Scroll Bar In The Data Dude Schema View

You won't find it.

There's no horizontal scroll bar in the schema view window like there is in the solution explorer (or other views).

The problem relevant for VS 2005 as also VS 2008.

scroll

Thursday, November 29, 2007

Visual Studio Team System 2008 Database Edition

vsdb

What has changed for Visual Studio Team Edition for Database Professionals (aka VSDB, DB Dude) in the 2008 edition?

  1. Installation: No more additional setup. In Visual Studio Team System 2008 VSDB completely integrated in the standard setup, so no more additional downloads. All you have to do is to make sure the Team Database Edition option is checked in the features to install window.  The database project functionality is only available in two of the Visual Studio Team System SKU's:
    • Visual Studio Team System 2008 Database Edition.
    • Visual Studio Team System 2008 Team Suite.
  2. The Visual Studio Team System 2008 Database Edition is based on the v1.0 functionality plus the Service Release 1 functionality.
  3. Solution Explorer performance improvements, especially when your project has large number of objects stored under a single node instead Solution Explorer.

What about the great features of VSDB 2005 power tools?  Not available yet. MS trying to release a new VSDB 2008 Power Tools release targeting later this month.

Saturday, November 10, 2007

Visual Studio 2008 Training Videos

Ready to learn about Visual Studio 2008? How it will make you more productive? Check out the training videos below.

http://msdn2.microsoft.com/en-us/vstudio/bb655906.aspx

Tuesday, November 6, 2007

VS2008 Language Support Presentation

You can download the first part of my presentation about VS2008.

The first part is about the new language features.

The agenda:

  • Multi-Targeting Support in VS 2008
  • Object Initializes
  • Lambda Expressions
  • Var Keyword
  • Automatic Properties
  • Extension Methods
  • Anonymous Types

Download from here.

Enjoy!

Monday, November 5, 2007

Release Date for Visual Studio 2008 and the .NET Framework 3.5

vs2008 Microsoft announced today that Visual Studio 2008 will be released before the end of November 2007.  Great News!

 

Technorati Tags:

Saturday, October 27, 2007

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

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 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

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!


Sunday, October 7, 2007

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!!

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: ,