background preloader

C#

Facebook Twitter

Dynamic

Covariance and Contravariance FAQ - C# Frequently Asked Questions. In this post I’ll try to answer the most common questions I find on forums and in documentation feedback about C# covariance and contravariance. It’s a big topic for a single blog post, so expect to see a lot of “more information” links. Special thanks to Eric Lippert and Chris Burrows for reviewing and providing helpful comments.

What are covariance and contravariance? In C#, covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments.Covariance preserves assignment compatibility and contravariance reverses it. The following code demonstrates the difference between assignment compatibility, covariance, and contravariance. // Assignment compatibility. string str = "test";// An object of a more derived type is assigned to an object of a less derived type. object obj = str;// Covariance.

In C#, variance is supported in the following scenarios: What is array covariance? Arrays are covariant since C# 1.0.

WCF

Nhibernate. Network. Message Queuing. Quartz Scheduler | Documentation | Tutorial Lesson 05. SimpleTrigger should meet your scheduling needs if you need to have a job execute exactly once at a specific moment in time, or at a specific moment in time followed by repeats at a specific interval. For example, if you want the trigger to fire at exactly 11:23:54 AM on January 13, 2015, or if you want it to fire at that time, and then fire five more times, every ten seconds.

With this description, you may not find it surprising to find that the properties of a SimpleTrigger include: a start-time, and end-time, a repeat count, and a repeat interval. All of these properties are exactly what you'd expect them to be, with only a couple special notes related to the end-time property. The repeat count can be zero, a positive integer, or the constant value SimpleTrigger.REPEAT_INDEFINITELY. The repeat interval property must be zero, or a positive long value, and represents a number of milliseconds. The endTime property (if it is specified) overrides the repeat count property. Quartz.Net - delay a simple trigger to start. C# - Quartz.net repeat job at interval after job is completed. Quartz.net with ASP.NET.

Synchronization

OData and Authentication – Part 6 – Custom Basic Authentication - WCF Data Services Team Blog. You might remember, from Part 5, that Basic Authentication is built-in to IIS. So why do we need ‘Custom’ Basic Authentication? Well if you are happy using windows users and passwords you don’t. That’s because the built-in Basic Authentication, uses the Basic Authentication protocol, to authenticate against the windows user database. If however you have a custom user/password database, perhaps it’s part of your application database, then you need ‘Custom’ Basic Authentication.

How does basic auth work? Basic authentication is a very simple authentication scheme, that should only be used in conjunction with SSL or in scenarios where security isn’t paramount. If you look at how a basic authentication header is fabricated, you can see why it is NOT secure by itself: var creds = "user" + ":" + "password"; var bcreds = Encoding.ASCII.GetBytes(creds); var base64Creds = Convert.ToBase64String(bcreds); authorizationHeader = "Basic " + base64Creds; Nevertheless many systems use basic authentication.

Using Reactive Extensions for Streaming Data from Database - About My Code. You have probably heard about Reactive Extensions, a library from Microsoft that greatly simplifies working with asynchronous data streams and allows to query them with Linq operators. There are many different scenarios where using rx results in a much more simple and flexible code. This post demonstrates how to use reactive extensions for loading data from database asynchronously in chunks. The Problem Recently I had to load data from sqlite database in grid view but the query was taking long time as there were hundreds of thousands of rows and the query was doing like %search term% filtering. The customer wanted to run the query in background and load data in chunks as they became available similar to sql server management studio. This way the grid would show first 200 available rows in the beginning and then when the next 200 rows were loaded they would be added to the grid and so on until the query completes.

Solution without Reactive Extensions Extending Reactive Extensions Solution. Trackable DTO’s: Taking N-Tier a Step Further with EF4 - DevelopMentor. Download code for this article here. There’s been some discussion lately in the blogosphere on Self-Tracking Entities in EF4 and how well they might fit into a heterogeneous environment, where a Java client might consume a .NET service that exposes Self-Tracking Entities. While STE’s are placed in an assembly that does not reference the Entity Framework, the way in which change state is preserved in an STE is overly complex and seems to be designed to make it easier for EF to transmit changes to the ObjectStateManager on the service side. If you look closely at the ObjectChangeTracker class that is generated for the client, you’ll see that it maintains metadata for navigation properties with items that have been added or removed, as well as original values and extended properties.

Requiring a non-.NET client to implement all that is asking an awful lot, and it couples the client too tightly to the service implementation. Fast forward to Entity Framework 4.0 and Visual Studio 2010. Added, Object lifetime management with Unity | Code through the pain. If you have been using inversion of control containers for a while you have most probably used some object lifetime management. The lifetime management enables reuse of existing object instances for subsequent resolution. It should be also responsible for controlling how the container will release resolved instances.

Unity offers lifetime management as classes derived from LifetimeManager. Lifetime managers in Unity are created once for each type's registration (there is an exception which I will discuss later). The following text discusses built-in lifetime managers, their behavior and usage. LifetimeManager The LifetimeManager is an abstract class implementing the ILifetimePolicy interface. GetValue - returns a stored object instance already associated with lifetime manager.SetValue - stores a new object instance in the lifetime manager.RemoveValue - removes stored instance from lifetime manager.

Examples use this test class: TransientLifetimeManager The example using transient instances: The ADO.Net Entity Framework, POCO Objects and You « Design Concepts And Code « Programming « Rob Sanders: Sanders Technology. Introduction Now if you are like me, you’ve probably had some interest in POCO (plain old CLR objects) objects for at least some time. They are an invaluable tool in the distributed systems and service oriented architecture areas, but up until now they’ve been inaccessible for those designs. In a nutshell, both LINQ to SQL and Entity Framework (v1) class entities did not support serialization for the purpose of stateless transport(such as web service communication).

This stems from the embedded context tracking attributes, and the design which stipulates a fairly poor experience for those daring enough to detach entities and “pass them around”. Enter the ADO.net Entity Framework v2.. ahem, version 4 which shipped in the early part of this year. Whilst the EFv4 doesn’t support POCO objects out of the box (you have to use an online template), it’s easy enough to accomplish with minimal effort. Now what follows, is based on a number of other articles floating around the Internet. Execution. Value Injecter - object(s) to -> object mapper. The ADO.Net Entity Framework, POCO Objects and You « Design Concepts And Code « Programming « Rob Sanders: Sanders Technology.

Introduction Now if you are like me, you’ve probably had some interest in POCO (plain old CLR objects) objects for at least some time. They are an invaluable tool in the distributed systems and service oriented architecture areas, but up until now they’ve been inaccessible for those designs. In a nutshell, both LINQ to SQL and Entity Framework (v1) class entities did not support serialization for the purpose of stateless transport(such as web service communication). This stems from the embedded context tracking attributes, and the design which stipulates a fairly poor experience for those daring enough to detach entities and “pass them around”. Enter the ADO.net Entity Framework v2.. ahem, version 4 which shipped in the early part of this year. Before we get into the nitty gritty of this particularly long post, I will direct your attention to the following MSDN article which covers most of the steps for harmonious life with POCO objects and WCF services.

The Data Model The Object Model. Custom WSDL Publication. The service in this sample is marked with two custom attributes. The first, the WsdlDocumentationAttribute, accepts a string in the constructor and can be applied to provide a contract interface or operation with a string that describes its usage. The second, WsdlParamOrReturnDocumentationAttribute, can be applied to return values or parameters to describe those values in the operation. The following example shows a service contract, ICalculator, described using these attributes. public void ExportContract(WsdlExporter exporter, WsdlContractConversionContext context) { if (contractDescription !

= null) { // Inside this block it is the contract-level comment attribute. // This.Text returns the string for the contract attribute. // Set the doc element; if this isn't done first, there is no XmlElement in the // DocumentElement property. context.WsdlPortType.Documentation = string.Empty; // Contract comments. This sample does not use Svcutil.exe. To set up, build, and run the sample.

DataContract Serializer and IsReference property « Zulfiqar's weblog. In .net Framework 3.5 SP1, DataContractSerializer supports by-ref object graph serialization by using the standard xsd:ID/xsd:IDREF attributes. You can set the IsReference=true on your DataContract definition and serializer will generate XML elements with IDs/IDREFs attributes and will link them together rather embedding them inside each other(default behavior). Also if you examine the XSD generated by WCF as part of the metadata export, it will also contain the standard ID/IDREF xml schema attributes.

Because of this, xml can be correctly parsed and understood by any framework in a standard way. This change will enable serialization of object graphs having circular references (which wasn’t possible previously – at least not without writing custom code) and will also reduce the size of the serialized xml. Let’s examine this change using the following DataContract definition: [DataContract] public class Employee [DataMember] public string Name { get; set; } public Employee Manager { get; set; }

WCF cyclic references support. WCF DataContract serializer isn't by default aware of cyclic object graphs. If you encounter the Object graph for type 'X.Y.Z' contains cycles and cannot be serialized if reference tracking is disabled error - read to the end. There is a simple solution and it's well documented in the Preserving Object Reference in WCF article. However the code is very chaotic and contains mistakes. I've made several classes to support a simple and powerful control over the DataContract serialization parameters.

Support classes Examples: CyclicReferencesAware applied to the whole interface: [ServiceContract] [CyclicReferencesAware(true)] public interface TestFacade { [OperationContract] void Hello(SomeData data); } CyclicReferencesAware applied to individual operation(s): [ServiceContract] public interface TestFacade { [OperationContract] [CyclicReferencesAware(true)] void Hello(SomeData data); } CyclicReferencesAware applied to the whole interface and individual operation(s): DateTime.ToString() Patterns. All the patterns: The patterns for DateTime.ToString ( 'd' ) : The patterns for DateTime.ToString ( 'D' ) : The patterns for DateTime.ToString ( 'f' ) : The patterns for DateTime.ToString ( 'F' ) : The patterns for DateTime.ToString ( 'g' ) : The patterns for DateTime.ToString ( 'G' ) : The patterns for DateTime.ToString ( 'm' ) : The patterns for DateTime.ToString ( 'r' ) : The patterns for DateTime.ToString ( 's' ) : The patterns for DateTime.ToString ( 'u' ) : The patterns for DateTime.ToString ( 'U' ) : The patterns for DateTime.ToString ( 'y' ) : Building a custom DateTime.ToString Patterns The following details the meaning of each pattern character.

||\c || Represents the escape character, and displays the character "c" as a literal when that character is preceded by the escape character (\). Any other character copies any other character to the result string, without affecting formatting Author Paul Hayman Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. C# - Custom object factory extension for Unity. The Truth About Value Types - Fabulous Adventures In Coding. Excelent post, Eric! By the way, I found your blog while searching for this subject (your older post). I think most of this "local variables are allways stored on the stack" conviction comes from unmanaged world.

One time, in an interview, one guy asked my about this, knowing that my primary programming language is C#. I really never cared about this until this situation, just because I choosed for a managed language and I can live with the idea that CLR is there to choose a better way to JIT my code. When I saw your post about "stack/heap storage is an implementation detail", it sounded like music for me. It's nice to know implementation details and how you can use them to get more performance, but I really don't think you need to close your mind to one idea. Recently I'm started working with C++ and unmanaged environment. In other words.

Anyway, thanks for the precious information and the great content in your blog. Regards, Eric Lemes. Jimmy Bogard's Blog | Strong opinions, weakly held. Can we define implicit conversions of enums in c# SaveOrUpdate Vs Update and Save in NHibernate. Pattern Matching in C# - Part 1. Monday, April 07, 2008 2:00 AM bart In the previous episode of this series we took a look at the concept of pattern matching as it exists in a couple of functional languages out there as well as how we're going to map it to C# 3.0 syntax.

We left off with the exercise of guesstimating the public contract of our Pattern`1 class based on this sample: string message = new Pattern<string>(x) .Match((string name) => new Person(name, 25), name => name + " is 25 years. ") .Match((int age) => new Person("John", age), age=> "John is " + age + " years. ") .Else(() => "Unmatched object"); A few observations to infer this contract: The type parameter T of Pattern<T> denotes the return type of the pattern. So, we already have something like: class Pattern<T> { public Pattern<T>(object o) { ... } public Pattern<T> Match(...) { ... } public T Else(...) { ... } } There's one big missing piece: the parameterization of the Match and Else methods.

Here's the full definition finally: What's there to unify? Pattern Matching in C# - Part 2. Tuesday, April 08, 2008 2:00 AM bart In our journey to find the perfect match, we've arrived at an interpreter-based pattern matcher in the previous post. Although there are quite some limitations and the syntax isn't as sweet as we'd like it to be, it's fully functional. However, what about the performance of our pattern matcher? Consider the following benchmark: Random rand = new Random(); var persons = new List<Person>(); for (int i = 0; i < 100000; i++) persons.Add(new Person("Bart", rand.Next(1, 10))); var watch = new Stopwatch(); var baseline = persons.Select(p => { Person person = p as Person; if (person ! This comparison is "fair enough" - given a series of 100,000 randomized Person objects, we want to find matches with age 5.

Correctness has proven to be okay, but speed has been proven to be a little problematic, but where's the bottleneck? Definitely the allocated bytes go much higher (notice I've reduced the number of iterations to only 1000). No rocket science so far. MEF - Arrange Act Assert. Managed Extensibility Framework - Building Composable Apps in .NET 4 with the Managed Extensibility Framework. Fluent Validation with MEF and PRISM. Events and Races - Fabulous Adventures In Coding. Dotfuscating Strong Named Assemblies. .NET-fu: Signing an Unsigned Assembly (without Delay Signing) - OJ's rants. Arrange Act Assert - Jag Reehal on Agile Development, ASP.NET MVC, Silverlight and all manner of good stuff. Windows® API Code Pack for Microsoft® .NET Framework. Actipro Software. Compiler - DSL: from DSL rules into C# expressions. Expression Trees (C# and Visual Basic) Validation in a DDD world.

LINQ: Building an IQueryable Provider - Part I - The Wayward WebLog. Download LINQPad. Irony - Language Implementation Kit/Grammar/Terminals. Irony - .NET Language Implementation Kit. - View Discussion. Writing Your First Visual Studio Language Service. WWW DSL using Irony - Part 1. Irony .NET Language Implementation Kit « <CharlieDigital /> Irony - .NET Language Implementation Kit. Writing Your First Domain Specific Language, Part 1 of 2. .net - How do I create this expression tree in C# How to: Use Expression Trees to Build Dynamic Queries (C# and Visual Basic)