Recently I attended a .NET 3.5 bootcamp. One week hands-on with LINQ, WCF, WPF and WF. Here are my notes:
Day 1, New language features
- Value types and references are stored on stack
- Objects are stored on heap
- Generices of value types are implemented by compiler generating a class for the value type
- Generic constraints: Name<T> where T: …
- Type cast is better performing than ‘as’ operator if there is no exception
- Var can only be used with as local variable
- You can specify access modifiers with automatic properties
- IEnumerable returns IEnumerator: Current, MoveNext()
- Yield return: Returns only what currently is necessary
- Aggregaton means wrapping an existing type
- Book tip: More Effective C# – 50 best practices
- Partial method: Always private no implementation in ‘base’ class, marked as partial
- Delegates, lambda expressions
- Extension methods
- Type inferences
- Type initializers
Day 2, LINQ
- Use XDocument for LINQ to XML
- IEnumerable extension methods are in System.Linq.Enumerable
- IQueryable extension methods are in System.Linq.Queryable
- LINQ to Entities allows querying of a meta-model of the data, multiple entities can map to one database table
- Join operator to join non-related tables. If tables are related use the generated properties
- Cross join with SelectMany and to functions as parameter
- Sub select simply placed within anonymous type in a select statement
- Outer join: use into operator (query syntax) or GroupJoin (lambda)
- Aggregate runs over a sequence an compares two consequetive items
- Take and Step operator
- Single throws an exception when it does not return exactly one item
- First returns the first item
- DefaultIfEmpty returns default value
- SequenceEqual uses hash-code to compare elements
- Untyped DataTable do not implement IEnumerable: DataTable.AsEnumerable() extension method
- Conversions: ToDicitionary, ToLookup, ToList, ToArray
- Check-out referencesource.microsoft.com for original .NET framework code
- Use .Field<type> with untyped DataSets in LINQ queries
- Log property on DataContext to show T-SQL statements at runtime
- LINQ keeps track of object id (CLR). Executing the same query twice returns the same objects
- StoredProcedures are automtically added to DataContext when generated
- To refresh DataContext right click on it and choose ‘Run custom tool’
- Concurrency issues: Update Check property whether you want to check for concurrency or not
- DataContext.SubmitChanges throws ChangeConflictException on concurrency error, use DataContext.ChangeConflicts to resolve
- Versioning of offline data: Use SQL Server timestamp and own code/stored procedures
- Entity framework: ESQL or LINQ to Entities
- EF items: Conceptual schema, stored schema, mapping specification
- OfType<type> extension method to select a specific EF type from a table
Day 3, WPF
- WPF: resolution independant because of vector based rendering
- Fat client: Contains all logic except database
- Thin client: User interface that runs in browser
- Smart client: Distributed system client with UI and some business logic
- Layout control: Grid, StackPanel (stacks elements), Canvas (like WIN forms), DockPanel
- Elements do need to have a Name property
- DockPanel has LastChildFills property, default is true
- Shortcut keys for label by prefix title with _ and specify Target property
- Funky tooltip for a button with <Button.ToolTip> and specify all items in there
- Dependent properties: Child elements can access all parents properties
- Menu, MenuItem (Header property is name of menu item)
- Binding to another element: {Binding elementName=…,Path=…}
- You can use data binding to a check box to e.g. toogle the visibility for controls in the window
- Grid sizes: 100 – fixed, * – for stretching, also relations 1/3 to 2/3 – * – 2*, auto – size according to the elements
- CTRL-K,D to reorder XAML
- ImageSourceConverter to load image from uri
- OpenFileDialog like in Win Forms
- ListBox binding: ItemsSource={Binding}, DisplayMemberPath="Name" – work on first DataContext found higher up in hirarchy
- INotifyPropertyChanged event to tell control that underlying data has changed, on lists and classes
- IBindingList or BindingList of T for lists
- To support Property changed databinding use: DataContext="{Binding ElementName=lbCategories,Path=SelectedItem,NotifyOnTargetUpdated=true}" TargetUpdated="Grid_TargetUpdated"
Day 4, WCF
- ListBox templates: DataTemplate for every item and ItemsPanelTemplate for enclosing template
- Four Tenets of SOA: Explicit boundaries, autonomous evolution, share schema and contract, policy based compatablility (protocol, transport, encoding)
- Autonomous means that no service uses code from other services, but calls it’s service interface instead. This is not practical in reality due to performance.
- Using business layer of other service can have following issues: Session state not used, Transaction control not used. Because these are properties of the service layer.
- SQL Server 2005 introduced schema names: You can freely specify table prefix
- WCF combines technologies – asmx, message queue, WSE, remoting, enterprise services.
- An endpoint has ABC: Address, Binding, Contract.
- Binding specifies transport, encoding and protocol.
- Instead of WSDL, WCF exposes a metadata exchange endpoint (MEX), is called by clients to generate proxy
- Client has the responsibility to close/dispose the proxy after use. Not important for http but e.g. for tcp.
- Messaging pattern: One way, request-reply, duplex (callback)
- Contracts: Service, message and data.
- WCF configuration editor: Open once from tools and after that via right-click on web.config.
- One endpoint per address
- URL Parameters: ?wsdl – wsdl, ?xsd=xsd2 – data contract
- Changing the service namespace in code splits the wsdl into two files – THIS is NOT compatible to other clients, e.g. Java
- Use the Name attribute on contracts to avoid breaking the contract when refactoring
- Wrap proxy in try/finally with check on ‘State != faulted’ due to WCF bug that tries to close the connection after an error/Exception occured. And that will only tell you that the connection could not be closed.
- Use ChannelFactory.CreateChannel and cast to ICommunicationObject to use WCF service without generated proxy
- Operations can also return derived type. Must be specified with ServiceKnownType attribute. Can also be registered in two other ways.
- Fault contracts: Specify FaultContract attribute on operation, are part of the WSDL, throw FaultException<..>()
- Normal exception handling is a part of the behaviour: Either generic or specific: Advanced/ServiceBehaviours/serviceDebug/IncludeExceptionDetailsInFaults
- Other service behaviours: Throttling, workflow, concurrency behaviour
- Service behaviours can also be specified with ServiceBehaviour attribute
- WCF is easily extensible. E.g. error handler (IErrorHandler) to react on exceptions. Can be chained, when HandleError returns false the next handler is called. HandleError method runs async. Implement IServiceBehavior on service and use ApplyDispatchBehavior method. Loop over serviceHostBase.ChannelDispatchers and add error handler to each ChannelDispatcher.ErrorHandlers. Alternatively implement IServiceBehavior on error handler class, derive it from Attribute and put attribute on service.
- HTTPS supplies transport layer, point to point security, works with server-side certificate holding private/public key pair, cannot be used for double-hop scenarios
- WSHttpBinding for message security
- WSFederationBinding for claims-based security
- NamedPipe is a memory mapped file
- Customize bindings: Create new under Binding and reference that in BindingConfiguration on Endpoint.
- WCF can be hosted in anything .NET executable: Need to include System.ServiceModel, System.Runtime.Serialization, uses ServiceHost class. Configure the service: Load contract from DLL, define endpoints (add mex), define behavior (add mex and debug), apply behavior.
- A mex endpoint exposes metadata for all real endpoints
- When working with multiple endpoints, specify the name in constructor when instantiating the Proxy
Day 5, WF
- Silverlight only support basic HTTP binding
- For hosting in IIS you do not need a mex endpoint. It is enough to enable ServiceBehavior/serviceMetadata/HttpGetEnabled.
- VS 2008 generated WCF proxy implements INotifyPropertyChanged behavior for all properties of the DTO.
- Silverlight is not binary compatible to .NET CLR. Requires rebuild.
- Project type: WCF Service library has references, simple service and starts generic test client
- Cross domain policy is needed for a Silverlight application when it runs against a WCF service on a different URL than it is deployed to.
- Silverlight can run from ASPX or HTML page by specifing the XAP package to run.
- Silverlight design is read only. XAML can be copied from WPF and modified to run:
– Rename Window.Resources to UserControl.Resources
– Replace Label with TextBlock
– Remove WrapPanel
– Replace GroupBox with Border
– Move inner XML of Buttons and the like to Content/Text property
– Binding syntax needs to be moved to code
– Use REST service to retrieve to image
– Move events hook-up from XAML to code
- IIS hosting advantages: Application pools to set identity, recylcing, ServiceHosts only activated when actually used
- WAS – Windows Activation Services (Windows Feature), WCF non-HTTP Activation in Features, requires IIS 7.0, add bindings in IIS Manager for net.pipe, net.tcp, …., enable used protocols on adavanced settings for the service in IIS manager
- Workflow saves state in between tasks -> resumable.
- Types of workflows: sequential or state based. Human workflows are often state based.
- Placed in UI and/or business layer.
- WF runtime: Persistance, Tracing
- WF host: create runtime and WF
- Activities: a. inherit Activity and override Execute or b. Use CodeActivity and assign eventhandler
- WF designer: Initial state, final state, add Code Activity, Delay and SetState to activities.
- WF in code: StartRuntime, Start Workflow (you can pass parameters here as Dictionary<>)
- Authoring modes: XOML only, XOML and code, code only
- To create WF persistence database run SQL scripts ‘SqlPersistenceService’ from 3.0 and 3.5 framework folder, PersistAndRestore WF type
- What happens after a state is finished: idle, persisted, unloaded
- WF can implement a service contract: Can be useful to collect data via multiple WebService calls and insert data into database in the end:
– Requires Session
– Set IsInitiating and IsTermenating on OperationContracts
– Dependency property in WF class if it is used by some WF activity (propdb snippet)
– Requires wsHttpContextBinding
– Add persistence provider to ServiceBehavior, add connection string to app.config/web.config to persistence database