Page 1 of 3 in the LINQ category Next Page

A question that comes up a lot is this: How do I tell my IIS Application or Virtual Directory to use ASP.NET 3.5 rather than ASP.NET 2.0?

Folks often go into the IIS6 or IIS7 manager and setup an AppPool and see a properties dialog like this, and when the pull down the option, they often expect to see .NET 3.0 and .NET 3.5 in the list and it's not there, and they freak out, rightfully so.

image

Here's an explanation of why this is confusing, and hopefully by the end, it won't be confusing anymore.

Marketing

This is where marketing and reality part ways. I didn't initially like the naming, because I assumed that each major version of the Framework meant a new CLR, but it's growing on me as I understand it more. I get now why they named them this way. Additional fundamentally new functionality has to be named something.

image

.NET 2.0

The meat of .NET is in %windir%\Microsoft.NET\Framework\v2.0.50727. That's where, along with the GAC (Global Assembly Cache) all the libraries and compilers you know and love live. When folks ask "where is .NET" I usually start here.

image

.NET 3.0

The addition of .NET 3.0 didn't mean new compilers or a new CLR. Instead, it's three major new libraries: WCF (Windows Communication Foundation née Indigo), WPF (Windows Presentation Foundation née Avalon) and Windows Workflow or WF.

image

Bottom line: Installing .NET 3.0 doesn't fundamentally change your system in any way you should fear. Your 2.0 apps still run on a system with 3.0 installed. They are 2.0 apps using the 2.0 compilers and 2.0 CLR.

imageTry this. If you go into Visual Studio and File | New | Project (or Web Site), take note of the drop down in the upper right corner.

Select ".NET Framework 3.0" and make a new "WCF Service" take a look at the web.config. Note that it's pretty conventional, and should look like a typical .NET 2.0 ASP.NET application with a few additional.

Basically, remember Framework version != CLR Version. If you configured an IIS Application to use .NET 2.0, you're talking about the 2.0 CLR. WCF Applications use the .NET 2.0 CLR with the new 3.0 WCF libraries.

  • .NET Framework 1.x = CLR 1.x
  • .NET Framework 2.0 = CLR 2.0
  • .NET Framework 3.0 = CLR 2.0
  • .NET Framework 3.5 = CLR 2.0 + (C# 3.0 | VB9)

You can also use the new 3.5 compilers and the 3.0 libraries, of course as well. Each subsumes the previous as seen in Tim Sneath's fine stacked diagram above.

image

In your new app's web.config, there's a <system.serviceModel> section that is WCF specific, but otherwise the web.config looks pretty 2.0 typical.

.NET 3.5

The marketing term ".NET Framework 3.5" refers to a few things. First, LINQ, which is huge, and includes new language compilers for C# and VB. Second, the REST support added to Windows Communication Foundation, as well as, third, the fact that ASP.NET AJAX is included, rather than a separate download as it was before in ASP.NET 2.0.

There's a few other things in .NET 3.5, like SP1 of .NET 2.0 to fix bugs, but one way to get an idea of what's been added in .NET 3.5 is to look in c:\windows\assembly. Here's just the 3.5 versioned assemblies in the GAC (Global Assembly Cache).

image

Also, looking in %windir%\Microsoft.NET\Framework\v3.5 we can see the new compilers, MSBuild Target files, etc.

image 

So, getting to answering the original question, try this experiment.

Go into Visual Studio and make a .NET 2.0 Web Site. Once it's loaded up, note your web.config. Next, right-click on the project and select Properties. Under Build, select 3.5 Framework.

image

Now, load up your web.config and notice the changes that just occurred. There's some new handlers that are added to support Ajax and some new ASP.NET Features, but the really important stuff is the <system.codedom> and the newly added assemblies in the assemblies section.

    <compilation debug="false">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
warningLevel="4">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
warningLevel="4">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="OptionInfer" value="true"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>

There's the magic. Well, not really magic, and there's nothing hidden. This where your web site is told what version of the compiler to use, and the new supporting libraries.

This is where you tell ASP.NET to use .NET 3.5, not in IIS. IIS AppPools know about CLR versions, not Framework and compiler versions, those are set by the application.

Now, this is just my opinion, but I like to name my AppPools in IIS like this...

image

...which looks the way my brain thinks it is even though it's not reality. I keep my 1.1, 2.0 and 3.5 applications all running under the same instance of IIS, but each in their own AppPool. Note again, the there's nothing keeping me from having 3.5 apps under my 2.0 AppPool, I just keep them tidy on my own.

Technorati Tags: ,,,


rocky0005-120wMy one-hundred-and-fifth podcast is up. I got a chance to sit down with Rocky Lhotka (blog) and talk about the direction data access, business objects and multi-tier development are going, as well as where he things LINQ fits into his view of CSLA.NET. CSLA.NET is Rocky's application development framework that supports his multi-tiered view of business application development.

Subscribe: Subscribe to Hanselminutes Subscribe to my Podcast in iTunes

If you have trouble downloading, or your download is slow, do try the torrent with µtorrent or another BitTorrent Downloader.

Do also remember the complete archives are always up and they have PDF Transcripts, a little known feature that show up a few weeks after each show.

Telerik is our sponsor for this show.

Check out their UI Suite of controls for ASP.NET. It's very hardcore stuff. One of the things I appreciate about Telerik is their commitment to completeness. For example, they have a page about their Right-to-Left support while some vendors have zero support, or don't bother testing. They also are committed to XHTML compliance and publish their roadmap. It's nice when your controls vendor is very transparent.

As I've said before this show comes to you with the audio expertise and stewardship of Carl Franklin. The name comes from Travis Illig, but the goal of the show is simple. Avoid wasting the listener's time. (and make the commute less boring)

Enjoy. Who knows what'll happen in the next show?



I was visiting a local company where a bunch of friends work and they asked how to get LINQ to SQL to use NOLOCK. They were explicitly asking how to get the SQL generated by LINQ to SQL to add the NOLOCK hints to the end.

However, with NOLOCK (even though "everyone" has used it at some point or another) is generally considered a last resort. Queries that use NOLOCK aren't guaranteed to return correct results or technically, return any results at all.  

SQL 2005 has snapshot-based isolation levels that prevent readers from blocking writers or writers from blocking readers without allowing dirty reads.

Now, I have said that NOLOCK has served me personally very well in the past on systems of some size, but I hear what folks who say no to NOLOCK are saying. It certainly depends on one's definition of "correct results." ;)

There's three ways to get the behavior your want. Using TransactionScope is the recommended way to affect the transaction options associated with the commands generated by either LINQ to SQL or LINQ to Entities.

LINQ to SQL also supports explicitly setting the transaction on the context, so you could get the connection from the context, open it, start a transaction, and set it on the context. This can be desirable if you think SQL 2005 is promoting transactions too often, but the preferred method is TransactionScope.

ProductsNewViewData viewData = new ProductsNewViewData();
using (var t = new TransactionScope(TransactionScopeOption.Required,
    new TransactionOptions { 
IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
})) { viewData.Suppliers = northwind.Suppliers.ToList(); viewData.Categories = northwind.Categories.ToList(); }

Here's an example where I used it in some recent code. This TransactionScope could be hidden (layered away) in your DAL (Data Access Layer) or in your Data Context directly if you wanted it to be neater.

A second way is that you can still create and call Stored Procedures (sprocs) from LINQ to SQL and those sprocs could include NOLOCK, TransactionScope is a better choice for LINQ to SQL or LINQ to Entity generated SQL if you feel that your query doesn't need to lock down the table(s) it's reading from.

Note that you'll want to be aware of which statement in your LINQ to SQL actually starts talking to the database. You can setup a query ahead of time and it won't be executed, for example, until someone calls ToList() or the like. It's at this point you'll want to wrap it in the using(TransactionScope){}.

Another third way you could set it at a DataContext level (which, to be clear, would affect every generated LINQ to SQL query executed on that context) would be to execute the command:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

...using the connection available inside your DataContext.

Thanks to David Browne and Michael Pizzo for their help on this!



Dear Reader, I present to you nineteenth in a infinite number of posts of "The Weekly Source Code."

At Mix, Clint Rutkas and I were messing around writing a plugin model for one of his apps. We were prototyping and I typed up this typical-looking plugin style code:

string[] filesToTest = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "plugins"), "*.dll");
foreach (string file in filesToTest)
{
    Assembly a = Assembly.LoadFrom(file);
    foreach (Type t in a.GetTypes())
    {
        if (!t.IsAbstract && t.BaseType == typeof(MyBaseClass))
        {
            myListOfInstances.Add((MyBaseClass)Activator.CreateInstance(t, credentials));
        }
    }
}

It's pretty straightforward and has little (read: no) error handling. It spins through the DLLs in the /plugins folder, loads them each (this should be more explicit rather than a blanket load of all dlls in a folder), then looks for any types that are derived from MyBaseClass that aren't abstract, then instantiates them and puts them in a list.

I'm going to quote Jeff Moser's very good blog post "What does it take to be a grandmaster" in both this post and the next one I write. It's that good. Seriously, go read it now, I'll wait here.

Jeff invokes Anders Heilsberg (Father of C# and LINQ) and:

"Anders' recent statement that future versions of C# will be about getting the programmer to declare "more of the what, and less of the how" with respect to how a result gets computed. A side effect of this is that your "chunks" tend to be more efficient for the runtime, and more importantly, your brain."

I'm going to repeat part I bolded. I like Programming Languages that allow me to declare "more of the what, and less of the how."  This how we tried to design the system at my last job and I automatically mentally migrate towards systems that encourage this kind of thinking.

So, back to the foreach loops above. My good friend (and fellow baby sign language fan) Kzu came by while Clint and I were working and suggested we turn this increasingly complex procedure into a LINQ query.

After a few tries, here's what we came up with.

myListOfInstances =
    (from file in Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "plugins"), "*.dll")
     let a = Assembly.LoadFrom(file)
     from t in a.GetTypes()
     where !t.IsAbstract && t.BaseType == typeof(MyBaseClass) 
     select (MyBaseClass)Activator.CreateInstance(t, credentials))
    .ToList();

This is all one line, with some whitespace for readability. It says the same thing as the first chunk of code, but for some minds, it might be easier to read. This isn't a very good example of LINQ shining, from my point of view even though I like reading it. Certainly there's nowhere (I can see) for me to put error handling code that catches a bad load or bad cast in this example. There are, however, a LOT of places within that single line that one could set a breakpoint.

A better example would be like the one Jeff uses:

var primes = new int[] { 2,3,5,7,11,13,17,19,13,29,31,37,41 };
var primeSum = 0;
for (int i = 0; i < primes.Length; i++)
{
primeSum += primes[i];
}

...or even...

var primes = new int[] { 2,3,5,7,11,13,17,19,13,29,31,37,41 };
var primeSum = 0;
foreach (int i in primes)
{
  primeSum += i;
}

...could be more easily written and read like:

var primes = new int[] { 2,3,5,7,11,13,17,19,13,29,31,37,41 };
var primeSum = primes.Sum();

where .Sum() is part of LINQ as Arrays are IEnumerable.

I totally recommend you go get the free, no-installer LINQPad that comes with 200 examples from C# in a Nutshell.

Here are a few examples that I think really typify pretty code; certainly an improvement over the standard procedural code I'd usually write:

var names = new[] { "Tom", "Dick", "Harry" }.Where(n => n.Length >= 4);

Here's onen that does quite a few things to a list in a fairly clean syntax:

string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };

var results =
     (
       from n in names
       where n.Contains("a")  // Filter elements
       orderby n.Length       // Sort elements
       select n.ToUpper()     // Translate each element (project)
     ).ToList();       	

What LINQ-style queries have you written that feel more what than how?

Related, ahem, LINQS



figure1 My one-hundred-and-second podcast is up. In this episode, I sit down with Michael Pizzo, the Principal Architect of the ADO.NET Entity Framework. He gets technically down and dirty pretty fast and I get answers to all the hard questions like "Are LINQ to SQL and LINQ to Entities competing?" and "Which one should I use?" A very cool guy and a fun interview that finally set my head straight about the data stack.

Subscribe: Subscribe to Hanselminutes Subscribe to my Podcast in iTunes

If you have trouble downloading, or your download is slow, do try the torrent with µtorrent or another BitTorrent Downloader.

Do also remember the complete archives are always up and they have PDF Transcripts, a little known feature that show up a few weeks after each show.

Telerik is our sponsor for this show.

Check out their UI Suite of controls for ASP.NET. It's very hardcore stuff. One of the things I appreciate about Telerik is their commitment to completeness. For example, they have a page about their Right-to-Left support while some vendors have zero support, or don't bother testing. They also are committed to XHTML compliance and publish their roadmap. It's nice when your controls vendor is very transparent.

As I've said before this show comes to you with the audio expertise and stewardship of Carl Franklin. The name comes from Travis Illig, but the goal of the show is simple. Avoid wasting the listener's time. (and make the commute less boring)

Enjoy. Who knows what'll happen in the next show?



It's funny when you work at a company that has as many small projects as it has big ones. I hear one of two things:

"Is _______ dead? I haven't heard anything in a month from _____ team's blog! It must be dead.

or

"Can you just stop with the 99 different ways to do _______? There's more happening that I can handle."

I'll try to help with the latter in the coming months. Even though we hear about technologies like LINQ to SQL and LINQ to Entities or ASP.NET MVC and WCF and get confused about if they are complementary, there is (usually) a plan behind the whole stack, even if that plan isn't very well-communicated. I'll do a diagram or two to help soon.

But first, looking at the Is ____ dead? question. It'd be cool if someone just dropped a blog post as a "ping" every few weeks like "We're still here! Nope, not dead!" kind of like an Out of Office Response, but for blogs.

For example, LINQ to XSD was mentioned in June of 2007, looked rockin' sweet, and then went silent. However, small teams like this continue to move the ball forward, but we (the outside world) don't hear from them. I'll try to find those projects and ping for the people.

Just yesterday, LINQ to XSD surfaced (I actually had a video call with them on Weds) with a new release.

LINQ to XSD creates .NET classes with much better fidelity than what's created with (the aging) XSD.exe. Now, of course, XSD.exe makes classes for XmlSerialization, while LINQ to XSD makes classes that use an XDocument (not XmlDocument) as the backing store, so we are comparing Apples to Carburetors, but if your goal is to get Objects that come from an XML source, you should take a look at LINQ to XSD.

For example, if I take one of the goofiest schemas, OFX, a financial services schema (disclosure, I was the Vendor Committee Chair for OFX for a few years so I'm to blame a bit) and run it through LinqToXml.exe, here's some differences.

For example, in the XSD for OFX there's some types like "Amount" that have Restriction Facets. The type is a string, but it must match a certain regular expression, like:

<xsd:simpleType name="AmountType">
    <xsd:restriction base="xsd:string">
        <xsd:maxLength value="32"/>
        <xsd:minLength value="1"/>
        <xsd:whiteSpace value="collapse"/>
        <xsd:pattern value="[\+\-]?[0-9]*(([0-9][,\.]?)|([,\.][0-9]))[0-9]*"/>
    </xsd:restriction>
</xsd:simpleType>

However, when that's turned into generated code via XSD.exe and XmlSerialization, we get:

private string amountField
  
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string AMOUNT {   
get {        
return this.amountField;    
}    
set {        
this.amountField = value;    
} }

Which kind of sucks, from a fidelity point of view. We've lost information, the restriction is gone and the Type is gone.

Here's the same thing generated with LINQ to XSD:

public sealed class AmountType {     
[DebuggerBrowsable(DebuggerBrowsableState.Never)]    
public static Microsoft.Xml.Schema.Linq.SimpleTypeValidator TypeDefinition =
new Microsoft.Xml.Schema.Linq.AtomicSimpleTypeValidator(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String),
new Microsoft.Xml.Schema.Linq.RestrictionFacets(((Microsoft.Xml.Schema.Linq.RestrictionFlags)(46)), null, 0, 0, null, null, 32, null, null, 1,
new string[] { "^(([\\+\\-]?[0-9]*(([0-9][,\\.]?)|([,\\.][0-9]))[0-9]*))$"}, 0, XmlSchemaWhiteSpace.Collapse));    
private AmountType() {} }

...and...then the accessor:

public string AMOUNT {     
get { XElement x = this.GetElement(XName.Get("AMOUNT", ""));        
return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype);     }
    set { this.SetElementWithValidation(XName.Get("AMOUNT", ""), value, "AMOUNT", global::ofx.net.types.Item2003.Item04.AmountType.TypeDefinition);     } }

Note that this is generated, so don't judge it on aesthetics, it's about the experience as a consumer of the API. This is cool because we don't lose anything, the mapping between CLR type and XSD type is clean enough, you get a real type, but you can still access it as a string. If you set a value it's validated on the fly.

Remember again, this is an interesting, if biased, comparison as LINQ to XSD uses an XDocument as the backing store and its properties access the DOM, while XSD.exe/XmlSerializer makes copies using dynamically generated temporary helpers and XmlReaders/XmlWriters to make Objects out of your Angle Brackets.

Another good example of a quiet team that still has cool stuff coming is LINQ to SQL as they update for SQL 2008.

Dear Reader, what's the best way for a team to tell you they are not dead?

Related Posts



A fellow emailed me earlier asking how to get the namespaces from an XML document, but he was having trouble because the XML had some XML declarations like <?foo?>.

A System.Xml Way

XPathDocument has two cool methods, GetNamespace(localName) and GetNamespaceInScope, but they need a currentNode to work with.

 string s = @"<?mso-infoPathSolution blah=""blah""?>
              <?mso-application progid=""InfoPath.Document"" versionProgid=""InfoPath.Document.2""?>
              <my:ICS203 xml:lang=""en-US"" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
           xmlns:my=""http://schemas.microsoft.com/office/infopath/2003/myXSD/2007-04-03T19:03:38""            
xmlns:xd=""http://schemas.microsoft.com/office/infopath/2003""> <my:HeaderData/></my:ICS203>"; XPathDocument x = new XPathDocument(new StringReader(s)); XPathNavigator foo = x.CreateNavigator(); foo.MoveToFollowing(XPathNodeType.Element); IDictionary<string, string> whatever = foo.GetNamespacesInScope(XmlNamespaceScope.All);

Once you're on the right note, in this case the first element, you can call GetNamespacesInScope and get a nice dictionary that has what you need inside it.

namespaces

I really like the System.Xml APIs, they make me happy.

A System.Xml + LINQ to XML Bridge Methods Way

How could we do this with the LINQ to XML namespace? Well, pretty much the same way with a much nicer first line (yes, this could be made smaller).

 XDocument y = XDocument.Parse(s);
 XPathNavigator poo = y.CreateNavigator();
 poo.MoveToFollowing(XPathNodeType.Element);
 IDictionary<string, string> dude = foo.GetNamespacesInScope(XmlNamespaceScope.All);

Notice that the CreateNavigator hanging off of XDocument is actually an extension method that is there because we included the System.Xml.XPath namespace. There are a whole series of "bridge" methods that make moving between LINQ to XML APIs and System.Xml APIs seamless.

image

See the (extension) there in the tooltip? There's also a different icon for extension methods when they show up in Intellisense. See the small blue-arrow added next to CreateNavigator?

image

These helper methods are "spot-welded" on to existing object instances when you import a namespace that defines them. They are also called 'mixins.'

A Purely LINQ to XML Way

I also wanted to see how this could be done using LINQ to XML proper.

 Disclaimer: We are comparing Apples and Oranges here, so say, "wow that query is not as terse or compact as GetNamespacesInScope." We're comparing one layer of abstraction to a lower one. We could certainly make a mixin for XElements called GetNamespacesInScope and we'd be back where we started. The System.Xml method GetNamespacesInScope is hiding all the hard work.

Big thanks to Ion Vasilian for setting me straight with this LINQ to XML Query!

First we load the XML into an XDocument and ask for the attributes hanging off the root, but we just want namespace declarations.

XDocument z = XDocument.Parse(s);
var result = z.Root.Attributes().
        Where(a => a.IsNamespaceDeclaration).
        GroupBy(a => a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName,
                a => XNamespace.Get(a.Value)).
        ToDictionary(g => g.Key, 
                     g => g.First());

Then we group them by namespace. Note the ternary operator ?: that returns "" for no namespace, else the namespaces local name as the key selector, and then gets an actual XNamespace.

Update: Ion wrote me and pointed out a mistake. I was calling z.Root.AncestorsAndSelf.Attributes, and I only needed to call z.Root.Attributes, or if I wanted to get all namespaces, z.Root.DescendantsAndSelf(). Thanks Ion!

Ion says: "z.Root.AncestorsAndSelf() says: from the root element of the document find all ancestors and the element itself. In other words only the root element. If you want to find the in-scope namespace declarations for a given element ‘e’, then on that element you’ll do e.AncestorsAndSelf(). In other words, starting from the given element ‘e’ walking up the ancestors path and including the element itself look for attributes that are namespace declarations and build a dictionary … Note that the question for in-scope namespace declarations is answered by walking up a path in the tree and not by doing a full traversal of the tree starting from a given point (a la e.DescendantsAndSelf())."

It can be confusing to figure out the various types of these variables like "a" and "g". In this example, "a" is an XAttribute because the call to Attributes() is of IEnumerable<XAttribute> and g is of type IGrouping<string, XNamespace>, gleaned from the expression inside of GroupBy().

We finish it off by taking the IGrouping and turning it into a dictionary with ToDictionary, selecting an appropriate key and the first At runtime "g" is an instance of System.Linq.Lookup<string, XNamespace>.Grouping which implements IGrouping, containing the namespace as an (and the only) element, subsequently retrieved with a call to First() and becomes the value side of the dictionary item.

image

Do also note one subtle detail. The System.Xml call to GetNamespacesInScope always includes the xmlns:xml namespace, declared implicitly. The LINQ query doesn't include this implicit namespace. Note also that these were sourced from XML Attributes and that the order of attributes is undefined (another way to say this is that attributes have no order.)



Page 1 of 3 in the LINQ category Next Page

Contact

Sponsors

On this page...

Tags

Calendar

<2008 April>
SunMonTueWedThuFriSat
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

Archives

Google Ads